Notes posted to Ruby

RSS feed
August 15, 2008
1 thank

Enumerable#all? and Hashes

When used on a hash and a block is provided, all? passes each key/value pair as a two-element array to the block, which you can “catch” as either:

  1. A two-element array, with the key in element 0 and its corresponding value in element 1, or

  2. Two separate items, the first being the key, the second being the corresponding value.

August 15, 2008
4 thanks

Using all? on Empty Arrays and Hashes

When applied to an empty array or hash, with or without a block, all? always returns true. That’s because with an empty collection, there are no values to process and return a false value. so, watch out, if your array or hash is empty for any reason you will get a true which might not be what you expect it to be.

August 14, 2008 - (v1_8_6_287)
1 thank
August 14, 2008 - (v1_8_6_287)
11 thanks

Convert an Array to a Hash

The Hash.[] method converts an even number of parameters to a Hash. (The Hash[] method depends on the Hash class, but don’t confuse the method with the class itself). For example:

Hash['A', 'a', 'B', 'b']
# => {"A"=>"a", "B"=>"b"}

You can convert an array to a hash using the Hash[] method:

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

The * (splat) operator converts the array into an argument list, as expected by Hash[].

You can similarly convert an array of arrays to a Hash, by adding flatten:

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

This also comes in handy when you have a list of words that you want to convert to a Hash:

  A a
  B b
  C c
# => {"A"=>"a", "B"=>"b", "C"=>"c"}
August 14, 2008
5 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

# => {'A' => 'a', 'B' => 'b', 'C' => 'c'}