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