in ,

Ruby Basics: Hashes

Creating an Empty Hash

A hash (or dictionary) is a set of key/value pairs.  In Ruby you can create an empty hash, using the notation:

my_hash = {}

or

my_hash = Hash.new

With the later format you can specify default values of the hash, using the syntax:

Hash.new{0}

where 0 is the default value, if no value is supplied.

Creating a Hash with Values

Traditionally you could do this with a format like:

my_hash = {“f_name” => “Brian, l_name =>”Warner”, “age” => 42}

Symbols used in Hashes

You can also use symbols as hash keys.  A good reason to use symbols over the hash rocket, is that symbols are immutable strings and only used once in memory.  Because of this, iterating over the hash or pulling data from the hash is faster if you use Symbols.

my_hash = {:first_name => “Brian”, :last_name=>”Warner”, :age => 42}

You can also write Hash Symbols in a newer fashion like so:

my_hash = {first_name: “Brian”, last_name: “Warner”, age: 42}

The later looks more like expected payloads you will get with JSON, and probably easier to read.

To see the speed difference between symbols and strings, consider running this code (taken from codecademy), that runs a benchmark against the two types:

require 'benchmark'
 
string_AZ = Hash[("a".."z").to_a.zip((1..26).to_a)]
symbol_AZ = Hash[(:a..:z).to_a.zip((1..26).to_a)]
 
string_time = Benchmark.realtime do
  100_000.times { string_AZ["r"] }
end
 
symbol_time = Benchmark.realtime do
  100_000.times { symbol_AZ[:r] }
end
 
puts "String time: #{string_time} seconds."
puts "Symbol time: #{symbol_time} seconds."

 

Pulling Values from the Hash

To get values from a hash is pretty easy.  In this example:

my_hash = {first_name: “Brian”, last_name: “Warner”, age: 42}

If I wanted the value for first_name, I would just use:

my_hash[:first_name]

Notice the colon goes to the front of the symbol (which is the standard notation for a symbol in Ruby.)  We use a convention in the hash that uses a colon at the end of the symbol, but when we call that symbol outside the hash, we need to reference it as :symbol_name.

If our hash didn’t use symbols, we could use the notation:

my_hash[“f_name”]

Of course that won’t work if you have a hash of symbols.  Where this might be useful, is in the parsing of JSON.  You might a call to a endpoint that returns JSON back to you.  A JSON parser will make up a hash (without symbols), and you would access it like the above.

Iterate through a Hash

If you want just the values from a hash map you can make use of the each method to iterate through the map and return the values like so:

my_hash = {first_name: "Brian", last_name: "Warner", age: 42}
 
my_hash.each do |x,y|
  puts y
end

If you wanted both the key and value, you would do:

my_hash = {first_name: "Brian", last_name: "Warner", age: 42}
 
my_hash.each do |x,y|
  puts x
  puts y
end

This is all pretty normal and basic stuff, but Ruby has some cool features in regards to selecting data from a hash…

Adding to the Hash

Lets say you want to add a new key and value to the hash. You can do so by doing:
my_hash[some_key] = some_value
If your hash uses symbols and your key/values are strings, try:
my_hash[some_key.to_sym] = some_value.to_symb

Deleting from a Hash

This is easy, just my_hash.delete(some_key)
If the key is a symbol, make sure to call it as such… or convert it like:
my_hash.delete(some_key.to_sym)

Cool Stuff: Selecting and other things…

Ruby lets you do some parsing right off the bat, with the select method.  Say for example you had a hash of people, and each key had a value of their age.  But let’s say you only want the hash to return people who are over the age of 30 years old… well select helps you do that.  In the example below, we have several people.  Each has a value that’s their age… so we call the select method to sort out only those values that match our criteria:

my_hash = {brian: 42, marry: 56, ellis: 88, carlyle: 3, chiana: 13}
 
puts my_hash.select{|name,age|age>;30}

What’s returned is:

{:brian=>42, :marry=>56, :ellis=>88}

That’s pretty cool.

We can also make use of the each_key and each_value methods like so:

my_hash = {brian: 42, marry: 56, ellis: 88, carlyle: 3, chiana: 13}
 
puts my_hash.each_key{|x| print x, " "}

That will return each key as output, followed by a space. Like:
brian marry ellis carlyle chiana

You can combine other methods here on that x (key.) But first we have to convert the symbol to a string… for example, since this hash uses symbols, we could write something like:

puts my_hash.each_key{|x| print x.to_s.reverse!, " "}

Which would output:
nairb yrram sille elylrac anaihc

Many possibilities here!

Similarly, the each_value method can be called to transform the values!

puts my_hash.each_value{|x| print x.to_s.reverse!, " "}

Which would output:
24 65 88 3 31

Now I like that one! It makes me much younger! Oh to be 24 again.

As you can see, there are many possibilities to easily transform hashes, quickly and easily – it’s also very readable.

Hang Ups

One of my early hang ups was on naming conventions.  In these examples, when I am iterating through a hash, or using the select method, I may use “name” and “age” as it is logical – but it has no baring on the actual call.  They are simply variables (placeholders.)

For example, in the above select… I could have written:

puts my_hash.select{|x,y| y > 30}

Ruby is assigning the first param (whatever I call it) to the key and the second param (whatever I call it) to the value in the hash.

What do you think?

0 points
Upvote Downvote

Total votes: 0

Upvotes: 0

Upvotes percentage: 0.000000%

Downvotes: 0

Downvotes percentage: 0.000000%

Written by Admin

I work for a Telecom company writing and testing software. My passion for writing code is expressed through this blog. It's my hope that it gives hope to any and all who are self-taught.

Comments

Leave a Reply

Loading…

Python Block Comments

Ruby Image Scraper