简体   繁体   中英

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. 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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM