我有一个字符串:
input # => 'make_me sandwich noodles coffee'
我想使用参数make_me
,sandwich
,noodles
调用coffee
方法:
make_me(sandwich, noodles, coffee)
我知道使用split
,并使用第一个数组元素作为方法名称,将遗骸作为参数。还有更好的方法吗?
答案 0 :(得分:2)
听起来很危险但是你走了:
command_with_args = input.split(" ")
send(command_with_args[0], *command_with_args[1..3])
答案 1 :(得分:1)
@akuhn和@Sooraj的致谢,我们需要使用split()
cmd, *args = gets.chomp().split(" ")
send(cmd, *args)
答案 2 :(得分:0)
假设你实际上是指字符串:
send(*input.split(" "))
如果您打算将每个参数作为方法,那么:
method, *args = input.split(" ")
send(method, *args.map{|arg| send(arg)})