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

Building Hashes


2 of 5

Hash Literals

This is by far the most common way to put data into a Hash. This is best suited for small hashes, one-off parameters to methods, or struct-like objects. The most common way to do this is the "rocket" syntax.

#!/usr/bin/env ruby

hash = {
 :key => 'value',
 :key2 => 'value2'

p hash

This is the easiest way to do this in all code up to version 1.9.2. There, a new syntax was introduced. And while this syntax works on 1.9.2, it won't work on earlier versions, so be aware before using it.

#!/usr/bin/env ruby

hash = {
 key: 'value',
 key2: 'value2'

p hash

This is a much cleaner syntax, and reduces the amount of "line noise" (AKA special characters) in your code. However, it makes the assumption that your key is going to be a symbol. If you're using any other objects as your keys (numbers, for example), you can't use this syntax.

  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. Hash Literals

©2014 About.com. All rights reserved.