5, "chips" => 2, "coke" => 1} end def receive_-6ren">
gpt4 book ai didi

ruby - 通过传递键数组使用 values_at 从 Ruby 哈希中提取值

转载 作者:太空宇宙 更新时间:2023-11-03 17:05:03 26 4
gpt4 key购买 nike

我正在尝试通过作为参数传入的键提取散列值:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com