Intro to Ruby - Hashes

Ruby

Overview

The following demonstrates the basics of Ruby hashes but there is much more to hashes so make sure to study the API.

The examples jump ahead a little as blocks are introduced via the use of brackets: {}. Brackets can both be used in the definition of a hash and a block of code. It is pretty cool to be able to write looping logic within one line of code isn’t it. More on loops soon but play with the hashes below first.

Code

# Basic initialization. The hash size is printed to show that the hash is new.
puts "01 Initialization\n\n"
h = Hash.new
puts h.size

# Another way to initialize a hash but with less typing. The hash size is printed to show that the hash is new.
puts "\n02 Alternative Initialization\n\n"
h = {}
puts h.size

# The following hash is initialized and then all the keys are printed.
puts "\n03 Hash Keys\n\n"
h = {:line_1 => "3030 Ruby Way", :city => "Colorado Springs", :state => "CO", :zip => 80808}
h.each_key {|key| puts key}

# Using the above hash, the values are printed instead.
puts "\n04 Hash Values\n\n"
h.each_value {|value| puts value}

# Using the above hash, the city value is found and printed.
puts "\n05 Grabbing Specific Values\n\n"
puts "City = " + h[:city]

# Using the above hash, the line_1 key and value is deleted.
puts "\n06 Deletion\n\n"
h.delete :line_1
puts h.inspect

# Using the above hash and a new hash (h2), we merge both into one and then print the result.
puts "\n07 Addition/Merging\n\n"
h2 = {:created_at => Time.now}
h.merge! h2
puts h.inspect

# Using the original hash, we clear it of all data and show that it is empty.
puts "\n08 Clearing\n\n"
h.clear
puts "Is hash empty?: " + h.empty?.to_s

Output

01 Initialization

0

02 Alternative Initialization

0

03 Hash Keys

line_1
city
state
zip

04 Hash Values

3030 Ruby Way
Colorado Springs
CO
80808

05 Grabbing Specific Values

City = Colorado Springs

06 Deletion

{:city=>"Colorado Springs", :state=>"CO", :zip=>80808}

07 Addition/Merging

{:city=>"Colorado Springs", :state=>"CO", :zip=>80808, :created_at=>Sun Feb 22 11:25:24 -0700 2009}

08 Clearing

Is hash empty?: true

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 05-hashes.rb.

What’s Next

Variables and Scopes

Tags:

Tuesday, February 24th, 2009 Software

No comments yet.

Leave a comment

You must be logged in to post a comment.