简体   繁体   中英

How to iterate through an array of hashes when there is a blank hash?

I have an array of hashes: @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. 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. 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. So it's nil even with non-empty Hashes.

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. 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?)

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