【问题标题】:Get array values using index key in Ruby on Rails在 Ruby on Rails 中使用索引键获取数组值
【发布时间】:2013-04-15 14:02:36
【问题描述】:

我正在遍历一个数组或哈希,我想根据索引获取值。

@lv = {'apple' => ['round', 'red'], 'more names' => ['tags', 'more tags']}

@lv.each do |key, value|
   # if the value is from the index key and equal to key itself...
end

我不确定如何从@lv 获取值。假设我想得到apple:

有没有像@lv[0] 这样的东西应该等于苹果?因为

[0] => apple
[1] => more names

对吗?

所以我可以

@lv.each do |key, value|
   if @lv[0] == key
     # apple equals apple, then proceed
   end
end

这样做的正确语法是什么?

谢谢!

【问题讨论】:

    标签: ruby-on-rails arrays loops key-value


    【解决方案1】:
    @lv.keys[0]   # => "apple"
    @lv.values[0] # => ["round", "red"]
    

    【讨论】:

    • 谢谢!这就是我要找的东西!
    猜你喜欢
    • 1970-01-01
    • 2014-06-20
    • 2011-04-19
    • 2015-12-04
    • 2018-06-06
    • 2014-09-08
    • 1970-01-01
    • 2023-03-04
    • 2014-05-03
    相关资源
    最近更新 更多