method

inject

Importance_4
Ruby latest stable (v1_8_6_287) - 5 notes - Class: Enumerable
inject(init) public

No documentation

This method has no description. You can help the Ruby community by adding new notes.

Show source
Register or log in to add new notes.
August 17, 2008
4 thanks

Re: Convert an Array of Arrays to a Hash using inject

If you’re sure you have a two-level array (no other arrays inside the pairs) and exactly two items in each pair, then it’s faster and shorter to use this:

  array = [['A', 'a'], ['B', 'b'], ['C', 'c']]
  hash = Hash[*array.flatten]

For more than two-level deep arrays this will give the wrong result or even an error (for some inputs).

  array = [['A', 'a'], ['B', 'b'], ['C', ['a', 'b', 'c']]]
  hash = Hash[*array.flatten]
  # => {"A"=>"a", "B"=>"b", "C"=>"a", "b"=>"c"}

But if you’re running Ruby 1.8.7 or greater you can pass an argument to Array#flatten and have it flatten only one level deep:

  # on Ruby 1.8.7+
  hash = Hash[*array.flatten(1)]
  # => {"A"=>"a", "B"=>"b", "C"=>["a", "b", "c"]}
August 14, 2008
4 thanks

Convert an Array of Arrays to a Hash using inject

Converting an array of arrays to a hash using inject:

  array = [['A', 'a'], ['B', 'b'], ['C', 'c']]

  hash = array.inject({}) do |memo, values|
    memo[values.first] = values.last
    memo
  end

  hash
  # => {'A' => 'a', 'B' => 'b', 'C' => 'c'}
December 2, 2008
2 thanks

From the official docs

  enum.inject(initial) {| memo, obj | block } => obj
  enum.inject {| memo, obj | block } => obj

Combines the elements of enum by applying the block to an accumulator value (memo) and each element in turn. At each step, memo is set to the value returned by the block. The first form lets you supply an initial value for memo. The second form uses the first element of the collection as a the initial value (and skips that element while iterating).

   # Sum some numbers
   (5..10).inject {|sum, n| sum + n }              #=> 45
   # Multiply some numbers
   (5..10).inject(1) {|product, n| product * n }   #=> 151200

   # find the longest word
   longest = %w{ cat sheep bear }.inject do |memo,word|
      memo.length > word.length ? memo : word
   end
   longest                                         #=> "sheep"

   # find the length of the longest word
   longest = %w{ cat sheep bear }.inject(0) do |memo,word|
      memo >= word.length ? memo : word.length
   end
   longest                                         #=> 5

http://www.ruby-doc.org/core/classes/Enumerable.html

December 6, 2008
2 thanks

Array expansion in blocks

The syntax can be improved as changing the second parameter of the block (values) and using an array of two variables instead, which will be used by Ruby as the key and value of "array".

  array = [['A', 'a'], ['B', 'b'], ['C', 'c']]

  hash = array.inject({}) do |memo, (key, value)|
    memo[key] = value
    memo
  end

  hash
  # => {'A' => 'a', 'B' => 'b', 'C' => 'c'}
August 14, 2008 - (v1_8_6_287)
1 thank