hash

Using Hash#values

Monday, July 28th, 2008 | Ruby on Rails | No Comments

This is minor, but I thought it was interesting nonetheless.

I needed to iterate through the values of a Hash. So I called .values on the Hash in question. What was interesting about this had nothing to do with the results of calling this method, but instead what it was actually doing to the Hash.

>> myhash = { :first => "one", :second => "two", :third => "three" }
=> {:second=>"two", :first=>"one", :third=>"three"}

The myhash how has a class of Hash, which is to be expected, since that's what I gave it.

>> myhash.class
=> Hash

When .values is called, it returns all of the values in the Hash.

>> myhash.values
=> ["one", "two", "three"]

You may have noticed this in that last example, but when .values was called on that Hash, the class of the result changed altogether. Let's examine the class of this Hash while we are calling .values on it.

>> myhash.values.class
=> Array

So calling .values on the Hash literally built an Array with the values from the preceding Hash!

Read more about Hash#values in the Ruby Documentation.

Tags: ,