简体   繁体   中英

How do I display specific key value pairs from a hash in the view?

I have a hash in my controller that a view takes data from to display. In the tutorials I've seen, I've learned how to display each of the key, value pairs from a hash...but how do I display only the key,value pairs I want?

    creating the hash in the controller
    @app = {'title' => title, 'description' => description,
            'active' => active, 'featured'=> featured,
            'partner'=>partner
            }

    view: this displays each of the key,value pairs
    <% @app.each do |key, value| %>
        <li><%= "#{key}: #{value}" %>
    <% end %>

    tried this in the view just to display title, but isn't working
    <% @app.select do |ind_app| %>
        <strong><%= ind_app["title"] %>
    <% end %>

If you want to display the title, just ask for the title! No need to loop, you can directly access all values of a hash like this :

<strong><%= @app['title'] %></strong>

you can try to get the pairs you want first. Try the following

<% @app.slice('title', 'active').each do |key, value| %>
    <li><%= "#{key}: #{value}" %>
<% end %>

This will only show the title and active part of the hash

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