使用Ruby on Rails中的索引键获取数组值

时间:2013-04-15 05:56:19

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

我正在迭代数组或散列,我想根据索引获取值。

@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

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

谢谢!

1 个答案:

答案 0 :(得分:5)

@lv.keys[0]   # => "apple"
@lv.values[0] # => ["round", "red"]
相关问题