Reputation: 8587
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. example:
someURL.com/?value=0
Then this is supposed to get the key apple
. I want to get the values from apple
which should be round
and 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?
Upvotes: 0
Views: 1137
Reputation: 663
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
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.
Upvotes: 1
Reputation: 160191
This makes no sense; @lv
is a map, not an array. 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.
@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.
Upvotes: 1