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

4

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

@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]应该等于apple的东西?因为

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

好的?

那么我可以

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

这该怎么做的语法是什么?
谢谢!
1个回答

6
@lv.keys[0]   # => "apple"
@lv.values[0] # => ["round", "red"]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接