Ruby on Rails:hash.each {} 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/430548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:54:04  来源:igfitidea点击:

Ruby on Rails: hash.each {} issues

ruby-on-railsrubyhash

提问by neezer

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. I run the same code in IRB and it works as expected.

我试过 .each_key & .each-value 与类似的块,它们都返回上面相同的字符串。我在 IRB 中运行相同的代码,它按预期工作。

What am I doing wrong?

我究竟做错了什么?

回答by Samuel

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.

您的问题是您正在使用 each 方法来构建您的字符串。你想要的是 map 方法。每个方法返回哈希值,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>

回答by Matt Haley

The problem is, putsreturns 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 @test2in your code sample is the return value of the .eachblock.

编辑:您@test2在代码示例中分配的是.each块的返回值。

回答by dylanfm

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

你可以把它放在你的视图中,而不是将它分配给一个变量。