Carlo Pecchia

Ruby 1.9: Hashes updated

(19.05.2010)

With Ruby 1.9 some little updates happened to Hashes too. Let’s see the major ones.

The first, and maybe more appreciated, is about the fact that now hashes are stable data structures. This means that insertion order of key-value pairs are preserved.

Another one is about string interpolation:

data = { name: 'Homer', age: 45}
puts "A smart guy like #{data[:name]} is #{data[:age]} years old."

can be rewritten as:

puts "A smart guy like %{name} is %{age} years old." % data

Definitelty more easy to manage.

Of course the “old” form is suppressed:

{:name, 'Homer', :age, 45}

Finally, another change that aims to armonize the Ruby language:

h = { :apples => 10, :bananas => 12, :cherries => 5 }
h.select{ |k,v| v > 5 }

With 1.8 we obtain:

[[:bananas, 12], [:apples, 10]]

That is an array of arrays… not so “close” to an hash :).

With 1.9 we - more consistently - have an hash:

{:apples=>10, :bananas=>12}
Italiano

Sei interessato a conoscere tutte le principali novità di Ruby 1.9?

Vedi lo screeencast "pillola" su ThinkCode.TV

Photo credits.