[英]How to iterate through an array of hashes when there is a blank hash?
I have an array of hashes: @grouped_messages
= 我有一个哈希数组:
@grouped_messages
=
[{},
{100=>[#<Message id: 3, content: "Needs more training", from: 100, employee_id: 1>]},
{101=>[#<Message id: 2, content: "Very lazy.", from: 101, employee_id: 2>], 102=>[#<Message id: 1, content: "Fantastic.", from: 102, employee_id: 2>]}]
One of the hashes is blank. 哈希值之一是空白。
How can I iterate through the array and display the contents without causing the following error: 如何遍历数组并显示内容而不会导致以下错误:
Error (undefined method `any?' for nil:NilClass)
I have tried the following but I still get the error: 我尝试了以下操作,但仍然收到错误消息:
<% if @grouped_messages.any? %>
<% @grouped_messages.each do |sender, messages| %>
<% if messages.any? %>
<% messages.each do |msg| %>
....
<% end %>
<% end %>
<% end %>
<% end %>
我会过滤以仅保留非空哈希:
@grouped_messages.reject(&:blank?).each ...
You can filter out empty Hashes like apneadiving suggests. 您可以像暂停呼吸一样过滤掉空的哈希。 However, there is another mistake in your code.
但是,您的代码中还有另一个错误。
@grouped_messages
is an Array of Hashes. @grouped_messages
是一个哈希数组。 You cannot do 你做不到
@grouped_messages.each do |sender, messages|
Using .each
on an Array yields a single value , in your case that's a Hash. 在数组上使用
.each
产生一个值 ,在您的情况下为哈希值。 So you should do: 因此,您应该执行以下操作:
@grouped_messages.each do |grouped_message|
grouped_message.each do |sender, messages|
# ...
end
end
In your case, your messages
variable is always nil
, as the Hash (eg, {100=>[ ... ]}
) will be stored in the sender
variable. 在您的情况下,您的
messages
变量始终为nil
,因为Hash(例如{100=>[ ... ]}
)将存储在sender
变量中。 So it's nil
even with non-empty Hashes. 因此,即使使用非空的哈希值,它也
nil
。
In fact, looking at your data, it's better to make @grouped_messages
a Hash instead, with as keys the sender ids and the values a list of Messages. 实际上,查看您的数据时,最好将
@grouped_messages
为哈希,而将发送者ID和值作为消息列表作为关键字。 So have a structure like: 所以有一个像这样的结构:
@grouped_messages = {
101 => [ msg1, msg2, ... msgN ],
102 => [ msg1, msg2, ... msgN ]
}
Then you can do your loop just fine: 然后就可以进行循环了:
@grouped_messages.each do |sender, messages|
# ...
end
Try this: 尝试这个:
<% @grouped_messages.reject(&:blank?).each do |sender, messages| %>
<% messages.each do |msg| %>
# ....
<% end %>
<% end %>
Remove the condition 删除条件
if messages.any?
and change the next line to 并将下一行更改为
messages.to_a.each do |msg|
...
使用纯Ruby删除空消息
@grouped_messages.reject(&:empty?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.