简体   繁体   中英

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
  else
    result[h] = 1
  end
  result
}

@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:

bozo3bubba4bonker5

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?

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 = records_hash.map { |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 -%>

or

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

The problem is, puts returns nil.

What you want to do is:

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

or something similar.

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

您可以将它放在视图中,而不是将其分配给变量。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM