Ruby 如何同时生成方法、数组和哈希的参数
我需要同时发送数组和哈希的方法参数。但不知道,怎么做。下面是一个例子:Ruby 如何同时生成方法、数组和哈希的参数,ruby,Ruby,我需要同时发送数组和哈希的方法参数。但不知道,怎么做。下面是一个例子: def method(here should be this argument) end 输出: 编辑: 根据OP的注释,这里是OP可以使用的代码: def add(*arg) @entries = {} arg.each_slice(2) do |a| @entries[a.first] = a.last end p @entries end add(1,2,3,4) 输出: 你所说的同时是什
def method(here should be this argument)
end
输出:
编辑:
根据OP的注释,这里是OP可以使用的代码:
def add(*arg)
@entries = {}
arg.each_slice(2) do |a| @entries[a.first] = a.last end
p @entries
end
add(1,2,3,4)
输出:
你所说的同时是什么意思?对象可以是任何一种类型?您好。我对这个参数使用“each”并得到错误。如何仅对数组使用“每个”?如何检查参数?这是我的代码:def add(defs)defs.each do | word,definition |@entries[word]=definition endend@JohnOggy
每个
只能接受一个参数。
[1, 2, 3, 4]
{1=>2, 3=>4}
[1, 2, 3]
"hash conversion not possible"
def add(*arg)
@entries = {}
arg.each_slice(2) do |a| @entries[a.first] = a.last end
p @entries
end
add(1,2,3,4)
{1=>2, 3=>4}