I am trying to iterate over a hash in my controller method:
@trsesh_counts.each do |trsesh_mode, trsesh_count|
@hash = "#{trsesh_mode} (#{trsesh_count})"
end
In my view, I call the instance variable @hash:
<% @trsesh_counts.each do |trsesh_mode, trsesh_count| %>
<%= "#{trsesh_mode} (#{trsesh_count})" %>
<% end %>
vs. <%= @hash %> where array = <%= @trsesh_counts %>
which outputs the following:
(7) Running (12) Weightlifting (1) vs. Weightlifting (1) where array = {""=>7, "Running"=>12, "Weightlifting"=>1}
why is the @hash instance variable fetching only the last key-value pair of the hash (Weightlifting (1))? How can I get @hash to output the entire hash like when I iterate in the view?
EDIT: for some reason I can call fetch on each key-value pair, but I still can’t iterate over each pair.
h = @trsesh_counts
@hash = h.fetch("Running")
… returns 12, the value for the “Running” key.
Your code isn’t working because you are reassigning the value of
@hasheach time you loop through@trsesh_counts. Also, I’ve kept your variable names for clarity, but I’d recommend changing the name of@hash, as it’s really a string, not a hash. Change your original code snippet to this:Note the initial assignment of
@hash = ""to an empty string, then the use of<<inside the each block. (I’ve also included a trailing space in the string value.) This will build up the value of@hashinstead of reassigning a new value to it on each iteration.This can also be shortened using
Enumerable#each_with_objectlike so: