Forum: Ruby on Rails Display keys and values of a hash

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
559322a6fb76d9bf252a8d846587f3ea?d=identicon&s=25 Toro (Guest)
on 2009-03-02 10:12
(Received via mailing list)
Hello,

I have a hash, represented by @hash. I want to display the keys and
values of @hash in my view.
I realize that if say one of keys was "ip_address" i could simple add
this to my view: <%= @hash['ip_address'] %>.
However! @hash changes...Thus I won't always have the same keys. I
need a way to show key and values of a hash without specifically
naming each key that I want in my view.

Any suggestions would be greatly appreciated.

Thanks,

Toro
992f6dd317a9b164e1efc5b674623f38?d=identicon&s=25 Michael Graff (Guest)
on 2009-03-02 10:17
(Received via mailing list)
This is a basic Ruby question.  You might want to look into buying a
primer on Ruby and learn the basics; it'll help you a lot.

<% @hash.each do |key, value| %>
  <%=h "#{key.to_s} #{value.to_s}" %>
<% end %>

You can iterate through hashes in many various ways, including sorting
them:

<% @hash.keys.sort.each do |key| %>
  <%=h "#{key.to_s} #{@hash[key]}" %>
<% end %>

If these are controlled by someone not you (that is, submitted by the
user) using <%=h ... %> ensures that any HTML contained within would
not render directly into the page, but instead convert < into &lt; and
so on.  This is a basic security measure.

--Michael

On Sun, Mar 1, 2009 at 8:02 PM, Toro <torymbrady@gmail.com> wrote:
>
> Any suggestions would be greatly appreciated.
>
> Thanks,
>
> Toro
>
> >
>



--
(Ruby, Rails, Random) blog:  http://skandragon.blogspot.com/
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-03-02 10:18
(Received via mailing list)
On Mar 2, 2:02 am, Toro <torymbr...@gmail.com> wrote:
> Hello,
>
> I have a hash, represented by @hash. I want to display the keys and
> values of @hash in my view.
> I realize that if say one of keys was "ip_address" i could simple add
> this to my view: <%= @hash['ip_address'] %>.
> However! @hash changes...Thus I won't always have the same keys. I
> need a way to show key and values of a hash without specifically
> naming each key that I want in my view.
>
Iterate over the hash with each ?

Fred
559322a6fb76d9bf252a8d846587f3ea?d=identicon&s=25 Toro (Guest)
on 2009-03-02 19:52
(Received via mailing list)
Thanks Michael!
This topic is locked and can not be replied to.