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:
.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.do |(user, group)|
is a block that receives each element of the collection and assigns it to the variablesuser
andgroup
. The variablesuser
andgroup
are placeholders that will take on the values of each element during each iteration.- Within the block, you can perform operations or modifications using the
user
andgroup
variables. - 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. - 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
Leave a Reply