1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Building Hashes


4 of 5


Hashes can be built by merging them with other hashes. This is most commonly used to provide a set of default values to hashes, and then overwrite them with a set of desired values without having to define every desired value.

In the following example, the method takes a hash as an argument. It then merges it with the defaults hash. This merging is done by iterating over the argument and, for every key, write that value from the argument hash into the defaults hash. And, like many Ruby methods, there are two variants. The merge method merges the two hashes and returns a third hash, leaving both intact. The merge! method destructively merges the two hashes.

#!/usr/bin/env ruby
require 'pp'

def meth(arg)
 defaults = {
    method: :fast,
    depth: 7,
    delay: 100,
    failure: :ignore

 opts = defaults.merge(arg)
 p opts

meth({method: :slow, failure: :retry})

  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. Merging

©2014 About.com. All rights reserved.