Ruby On Rails // each_with_object ({}) do

The code .each_with_object({}) do |user, group| is part of an each loop that iterates over a collection, such as an array or a hash, and builds a new object (group) based on the elements of the collection.

Here’s an explanation of the code:

  1. .each_with_object({}) is a method called on a collection object (e.g., an array or a hash). It takes an initial object ({} in this case) as an argument and returns a new object (the one provided as an argument) with modifications made during the iteration.
  2. do |(user, group)| is a block that receives each element of the collection and assigns it to the variables user and group. The variables user and group are placeholders that will take on the values of each element during each iteration.
  3. Within the block, you can perform operations or modifications using the user and group variables.
  4. The block is executed for each element in the collection, and the modifications made within the block are applied to the object passed as an argument ({}) during each iteration.
  5. At the end of the loop, the modified object ({}) is returned as the result of the .each_with_object({}) method.

This code pattern is useful when you want to iterate over a collection and build a new object based on the elements in the collection. In your specific case, the user and group variables would represent individual elements from the collection, and you can perform operations on them to update the group object during each iteration.

Official documentation for each_with_object > https://rubydoc.info/stdlib/core/Enumerable:each_with_object

When converting your projects from old Ruby On Rails version to Ruby On Rails >6.0 you will eventually get an error like

undefined method `[]’ for nil:NilClass when trying to get Enumerator on an Array of Hashes

Or

NoMethodError – undefined method `[]’ for nil:NilClass

It happened to me because originally I wrote the code this way

The code .each_with_object({}) do |(user, group)|

Instead it will now only accept

The code .each_with_object({}) do |user, group|

Hope it helps!

Here is the complete code I used for iteration.

users.each_with_object({}) do |user, group|
  next unless user.categories.pluck(:id).include?(category) || user.categories.empty?

  group[user.role.name] = [] if group[user.role.name].nil?
  group[user.role.name] << [user.full_name, user.id]
end

Here is a link if you know more about the error NoMethodError

https://dev.to/ben/nomethoderror-undefined-method-for-nil-nilclass-explained-422b


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *