SHARE
TWEET

Untitled

a guest Feb 22nd, 2012 10 Never
  1. # BASIC USAGE
  2. # inject takes
  3. # sum -> item
  4. # 1   -> 2
  5. # 3   -> 3
  6. # 6   -> 4
  7. # 10  -> 5
  8. p (1..10).inject { |sum, item| sum + item }
  9. # => 55
  10.  
  11. # Ruby 1.9 shortcut
  12. p (1..10).inject(:+)
  13. # => 55
  14.  
  15. # ... this is more interesting stuff
  16. array = [Kernel, Object, Class, Module]
  17. p array.inject(Hash.new) { |hash, klass| hash[klass] = klass.methods.size; hash }
  18. # {Kernel=>144, Object=>92, Class=>93, Module=>93}
  19.  
  20. p (1..10).inject { |altogether, item| "#{altogether}, #{item}" }
  21. # "1, 2, 3, 4, 5, 6, 7, 8, 9, 10"
  22.  
  23. # So basically if inject is called with argument, this argument is placed as first block argument in first iteraction. Otherwise the first item of collection is used. Block is called and the returned value is passed again as first argument of block in next iteraction. This collected value is also returned at the end.
RAW Paste Data
Top