我正在尝试通过作为参数传入的键提取散列值:
def menu
@menu = {"burger" => 5, "chips" => 2, "coke" => 1}
end
def receive_order(*items)
raise "Sorry not in stock" if items.all? { |key|@menu.has_key?(key) } == false
:ordered if items.all? { |key|@menu.has_key?(key) }
# I was hoping to do something like this...
bill << menu.values_at(items)
# bill being an empty array
end
我在 IRB 中尝试过这个,它返回 [nil]
。谁能解释一下为什么?
如果我输入以下内容:
menu.values_at("burger", "chips")
我得到:
=> [5,2]
那么为什么当作为参数传入时它不起作用?
最佳答案
Hash#values_at
将工作如果你 splat the array而不是传递数组本身。
在发布的示例中,Hash
中的方法 values_at
将传递的数组视为单个键,而不是将数组的各个元素视为单独的键。
尝试:
bill << menu.values_at(*items)
REPL 中的示例(irb
/pry
):
>> hash = {a: 12, b: 7, c: 23}
=> {:a=>12, :b=>7, :c=>23}
>> keys_to_search = [:a, :b]
=> [:a, :b]
>> hash.values_at keys_to_search
=> [nil]
>> hash.values_at *keys_to_search
=> [12, 7]
关于ruby - 通过传递键数组使用 values_at 从 Ruby 哈希中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27708671/