SUPPORT THE SITE WITH A CLICK

Subscribe Rss:

SUPPORT THE SITE WITH A CLICK

Saturday, May 22, 2010

Hashes in ruby 1.9

Hashes in Ruby 1.9 are ordered collections, thats a big difference when compared to its previous versions, where hashes are unordered.Hashes store objects in pairs, each pair consisting of a key and a value.We can retrieve a value by means of the key.Hashes identifies the order in which their keys were inserted.

In hash, keys are unique, you can have only one key/value pair for any given key.Even if we don't use integers, hashes exhibit a kind of "meta-index"
property, based on the fact that they have a certain number of key/value pairs and that those pairs can be counted off consecutively.Let try this property in action by stepping a hash with the each_with_index, which yields a counter value to the block along with the key and value:


irb(main):031:0> hash.each_with_index{|(x,y),h| puts x}
david
matz
wycats
=> {"david"=>"rails", "matz"=>"ruby", "wycats"=>"merb"}

irb(main):032:0> hash.each_with_index{|(x,y),h| puts y}
rails
ruby
merb
=> {"david"=>"rails", "matz"=>"ruby", "wycats"=>"merb"}

irb(main):033:0> hash.each_with_index{|(x,y),h| puts h}
0
1
2
=> {"david"=>"rails", "matz"=>"ruby", "wycats"=>"merb"}
irb(main):034:0>

No comments :

Post a Comment