gpt4 book ai didi

ruby-on-rails - 获取 ruby 的值(value)

转载 作者:数据小太阳 更新时间:2023-10-29 08:18:49 25 4
gpt4 key购买 nike

在 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"

关于ruby-on-rails - 获取 ruby 的值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12865919/

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