Ruby-on-rails – Ruby on Rails: hash.each {} issues


Here is my code:

records_hash = records[:id].inject({}) { |result,h|
  if result.has_key?(h)
    result[h] += 1
    result[h] = 1

@test2 = records_hash.each{|key,value| puts "#{key} is #{value}"}

My output should look like this:

bozo is 3
bubba is 4
bonker is 5

But it renders on the page (<%= @test2 %>) as this:


I've tried .each_key & .each-value with similar blocks and they all return the same string above. I run the same code in IRB and it works as expected.

What am I doing wrong?

Best Solution

Your problem is that you are using the each method to build your string. What you want is the map method. each method returns the hash and map returns the value of the block.

You want something like this:

@test2 = { |k,v| "#{k} is #{v}" }

Also, you shouldn't be building view code like this, unless it is a simple string. Your example implies you want each unique element on each line. So your view should be like this:

<% @records_hash.each do |k,v| %>
<%= "#{k} is #{v}" %>
<% end -%>

If your view is an HTML one, you'll want some separator between each line as well:

<% @records_hash.each do |k,v| %>
<%= "#{k} is #{v}" %><br/>
<% end -%>


  <% @records_hash.each do |k,v| %>
  <li><%= "#{k} is #{v}" %></li>
  <% end -%>