Advertisement
Guest User

Untitled

a guest
Sep 30th, 2018
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.99 KB | None | 0 0
  1. https://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-inject
  2.  
  3.   inject -  is that as you loop through each element of your enumerable object, a second accumulator value is passed in as well.
  4.   The accumulator value is updated on each iteration and eventually returned.
  5.  
  6.   (1..5).inject(0){ |sum, num| sum + num } ==> returns 15
  7.   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.
  8.  
  9.  
  10.   We are passing in an empty hash as the initial value for our accumulator.
  11.   We are calling the merge method on our accumulator hash each iteration.
  12.   This method returns an updated hash as our new accumulator.
  13.  
  14.   users = User.all
  15.   users.inject({}) do |memo, user|
  16.     memo.merge(user.email => user.email)
  17.   end
  18.  
  19.   => {"schamane.vzl@gmail.com"=>"schamane.vzl@gmail.com",
  20.    "jannet@gmail.com"=>"jannet@gmail.com",
  21.    "supersimple2@mail.ru"=>"supersimple2@mail.ru",
  22.    "schamane2.vzl@gmail.com"=>"schamane2.vzl@gmail.com",
  23.    "schamane.vzl1@gmail.com"=>"schamane.vzl1@gmail.com",
  24.    "admin@example.com"=>"admin@example.com"}
  25.  
  26. In inject, the order of the arguments are |accumulator, element|
  27.  
  28. https://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-each_with_object
  29.  
  30.   users = User.all
  31.   users.each_with_object({}) do |user, memo|
  32.     memo[user.email] = user.email
  33.   end
  34.  
  35.   => {"schamane.vzl@gmail.com"=>"schamane.vzl@gmail.com",
  36.    "jannet@gmail.com"=>"jannet@gmail.com",
  37.    "supersimple2@mail.ru"=>"supersimple2@mail.ru",
  38.    "schamane2.vzl@gmail.com"=>"schamane2.vzl@gmail.com",
  39.    "schamane.vzl1@gmail.com"=>"schamane.vzl1@gmail.com",
  40.    "admin@example.com"=>"admin@example.com"}
  41.  
  42. The each_with_object method ignores the return value of the block and only passes the initial accumulator object along to the next iteration.
  43. This is why we don’t need to use the merge method here.
  44.  
  45. in each_with_object the order of the arguments are |element, accumulator|
  46.  
  47. https://medium.com/@Fdel15/ruby-each-with-object-or-inject-a737bb90cdd8
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement