Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-inject
- inject - is that as you loop through each element of your enumerable object, a second accumulator value is passed in as well.
- The accumulator value is updated on each iteration and eventually returned.
- (1..5).inject(0){ |sum, num| sum + num } ==> returns 15
- This example simply keeps track of a sum variable and adds each number in the array to it and then returns the sum at the end.
- We are passing in an empty hash as the initial value for our accumulator.
- We are calling the merge method on our accumulator hash each iteration.
- This method returns an updated hash as our new accumulator.
- users = User.all
- users.inject({}) do |memo, user|
- memo.merge(user.email => user.email)
- end
- => {"schamane.vzl@gmail.com"=>"schamane.vzl@gmail.com",
- "jannet@gmail.com"=>"jannet@gmail.com",
- "supersimple2@mail.ru"=>"supersimple2@mail.ru",
- "schamane2.vzl@gmail.com"=>"schamane2.vzl@gmail.com",
- "schamane.vzl1@gmail.com"=>"schamane.vzl1@gmail.com",
- "admin@example.com"=>"admin@example.com"}
- In inject, the order of the arguments are |accumulator, element|
- https://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-each_with_object
- users = User.all
- users.each_with_object({}) do |user, memo|
- memo[user.email] = user.email
- end
- => {"schamane.vzl@gmail.com"=>"schamane.vzl@gmail.com",
- "jannet@gmail.com"=>"jannet@gmail.com",
- "supersimple2@mail.ru"=>"supersimple2@mail.ru",
- "schamane2.vzl@gmail.com"=>"schamane2.vzl@gmail.com",
- "schamane.vzl1@gmail.com"=>"schamane.vzl1@gmail.com",
- "admin@example.com"=>"admin@example.com"}
- The each_with_object method ignores the return value of the block and only passes the initial accumulator object along to the next iteration.
- This is why we donβt need to use the merge method here.
- in each_with_object the order of the arguments are |element, accumulator|
- https://medium.com/@Fdel15/ruby-each-with-object-or-inject-a737bb90cdd8
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement