[英]Ruby on Rails: iterating through array with specific index?
How do I iterate through an array if I have the specific index? 如果我有特定的索引,如何遍历数组?
@lv = {'apple' => ['round', 'red'], 'name' => ['tags', 'more tags']}
if params[:value]
@lv.each do |key, tags|
if params[:value] == key
tags.each_with_index do |tag, index|
... should display round and red?
end
end
end
end
I have an array @lv
and I want to be able to get the values if there's a parameter associated with it. 我有一个数组
@lv
,我希望能够获得值,如果有一个参数与它相关联。 example: 例:
someURL.com/?value=0
Then this is supposed to get the key apple
. someURL.com/?value=0
那么这应该是关键的apple
。 I want to get the values from apple
which should be round
and red
. 我想从
apple
获得应该是round
和red
。 My logic in the above codes is wrong, but I'm trying to figure out what is the syntax to call out the correct key to iterate? 我在上面的代码中的逻辑是错误的,但我想弄清楚调用正确的迭代键的语法是什么?
This makes no sense; 这毫无意义;
@lv
is a map, not an array. @lv
是一个地图,而不是一个数组。 Using numeric indices on a map is strange. 在地图上使用数字索引很奇怪。
You can rely on insertion order in Ruby 1.9+, so @lv[@lv.keys[params[:value].to_i]]
would actually retrieve what you want, but IMO it's semantically sketchy. 你可以依赖Ruby 1.9+中的插入顺序,所以
@lv[@lv.keys[params[:value].to_i]]
实际上会检索你想要的东西,但IMO它在语义上是粗略的。
@lv[@lv.keys[params[:value].to_i]].each_with_index do |tag, index|
...
end
I'd also recommend using at least one intermediate variable to clean up that expression. 我还建议使用至少一个中间变量来清理该表达式。
This seems like a lot of effort to make it work this way. 这似乎需要付出很多努力才能使它以这种方式工作。 Why not change the view so you can select the key name:
为什么不更改视图以便您可以选择密钥名称:
http://example.com/?value=apple
instead of http://example.com?value=0
http://example.com/?value=apple
而不是http://example.com?value=0
then you can change your controller code to: 那么您可以将控制器代码更改为:
@tags = @lv[params['value']]
Then just iterate through @tags
in your view, or whatever else you're trying to do with the list of tags. 然后在您的视图中迭代
@tags
,或者您尝试使用标记列表执行的任何其他操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.