1. Computing

Building Hashes


3 of 5

Serialized Hashes

Storing your hash in a text file has numerous advantages. First, it can be edited without touching your code. Second, it can be sent over the network as a normal file, and you don't have to worry about loading code from a third party. Third, it's used to inter-operate with other software, such as sending Javascript a hash encoded in JSON.

There are two very popular ways to serialize a hash: YAML and JSON.

YAML is "YAML ain't markup language." It's used throughout the Ruby world for a number of things, simple serialization and configuration files being the most common. It has a pretty simple syntax, using whitespace to structure the document. First, what the YAML document looks like. It has a single hash called "languages," which contains 3 key/value pairs.

 ruby: awesome
 python: also awesome
 perl: line noise

And the code to load this.

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

yaml = YAML::load( File.open('hash.yaml') )
hash = yaml['languages']

p hash

Notice one change between this and the previous hashes: the keys are strings instead of symbols. Other than that, the hash that it produces is the same as one from a Hash literal.

Next is JSON, another common markup language like YAML. However, it relies less on whitespace for formatting, and is preferred in places over YAML.

 "languages": {
    "ruby": "awesome",
    "python": "also awesome",
    "perl": "line noise"

And the code to load this hash. Note that this will only work on Ruby 1.9.2.

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

json = JSON.load( File.read('hash.json') )
hash = json['languages']

p hash

Note, again, that strings are used for keys instead of symbols.

  1. About.com
  2. Computing
  3. Ruby
  4. Beginning Ruby
  5. Serialized Hashes

©2014 About.com. All rights reserved.