在 ruby 中,我有
res = [[0, :product, "client"], [0, :os, "windows"], [0, :architecture, "32rs"]]
我想获得操作系统的值(value)。我可以通过 res[1][2] 来完成,但我不想依赖索引,因为它可以更改。我拥有的是 key ,即 :os,那么找到它的最佳方法是什么?
请您参考如下方法:
假设您无法更改数据的结构方式,您可以这样做:
res.select{|h| h.include?(:os)}.map(&:last)
但在我看来,您的数据最好用散列来表示。
res_hash = res.each_with_object({}) do |value, memo|
memo[value[1]] = value[2]
end
# => {:product=>"client", :os=>"windows", :architecture=>"32rs"}
然后您可以像这样访问离散数据属性:
res_hash[:os]
# => "windows"