Display keys and values of a hash

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

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 < and
so on. This is a basic security measure.

–Michael

On Sun, Mar 1, 2009 at 8:02 PM, Toro [email protected] wrote:

Any suggestions would be greatly appreciated.

Thanks,

Toro


(Ruby, Rails, Random) blog: http://skandragon.blogspot.com/

On Mar 2, 2:02 am, Toro [email protected] 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

Thanks Michael!