简体   繁体   English

Ruby on Rails:hash.each {}问题

[英]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: 但它在页面上呈现( <%= @test2 %> ),如下所示:

bozo3bubba4bonker5

I've tried .each_key & .each-value with similar blocks and they all return the same string above. 我尝试过类似块的.each_key和.each-value,它们都返回上面相同的字符串。 I run the same code in IRB and it works as expected. 我在IRB中运行相同的代码,它按预期工作。

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. 你想要的是map方法。 each method returns the hash and map returns the value of the block. 每个方法返回哈希值,map返回块的值。

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: 如果您的视图是HTML视图,那么您还需要在每一行之间使用一些分隔符:

<% @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. 问题是, puts收益为零。

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. 编辑:您在代码示例中为@test2分配的内容是.each块的返回值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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