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

hel*_*llo 4 arrays loops ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)

我不确定如何从中获取价值@lv.让我们说我想得到apple:

有没有像@lv[0]苹果一样的东西?因为

[0] => apple
[1] => more names
Run Code Online (Sandbox Code Playgroud)

对?

所以我可以

@lv.each do |key, value|
   if @lv[0] == key
     # apple equals apple, then proceed
   end
end
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

jdo*_*doe 5

@lv.keys[0]   # => "apple"
@lv.values[0] # => ["round", "red"]
Run Code Online (Sandbox Code Playgroud)