[ACCEPTED]-Ruby on Rails: hash.each {} issues-hash

Accepted answer
Score: 43

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

You 7 want something like this:

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

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

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

If your view 2 is an HTML one, you'll want some separator 1 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 -%>
Score: 1

The problem is, puts returns nil.

What you want 3 to do is:

@test2 = ""
@test2 = records_hash.each { |k,v| s<< "#{k} is #{v}" }

or something similar.

Edit: What 2 you're assigning to @test2 in your code sample 1 is the return value of the .each block.

Score: 0

You could just put that in your view, rather 1 than assigning it to a variable.

More Related questions