Ruby 1.9.1: Hash

Published on Author Akhil BansalLeave a comment

In ruby 1.9.1 has many changes for Hash some useful changes are below:

RUBY_VERSION => 1.8.6

RUBY_VERSION => 1.9.1

>> {'name', "Akhil"}
=> syntax error, unexpected ',', expecting tASSOC

>> {name: "Akhil"}
=> {:name=>"Akhil"}

Now Hash preserves order:

RUBY_VERSION => 1.8.6

>> hash = {:a=> 'A', :b=>'B', :c=>'C', :d=>'D'}
=> {:b=>"B", :c=>"C", :d=>"D", :a=>"A"}
>> hash.to_a
=> [[:b, "B"], [:c, "C"], [:d, "D"], [:a, "A"]]
>> hash.keys
=> [:b, :c, :d, :a]
>> hash.values
=> ["B", "C", "D", "A"]

RUBY_VERSION => 1.9.1

>> hash = {:a=> 'A', :b=>'B', :c=>'C', :d=>'D'}
=> {:a=>"A", :b=>"B", :c=>"C", :d=>"D"}
>> hash.to_a
=> [[:a, "A"], [:b, "B"], [:c, "C"], [:d, "D"]]
>> hash.keys
=> [:a, :b, :c, :d]
>> hash.values
=> ["A", "B", "C", "D"]

Better to_s method(similar to hash.inspect).

RUBY_VERSION => 1.8.6

>> hash = {:a=> 1, :b=>2, :c=>3, :d=>4}
=> {:b=>2, :c=>3, :d=>4, :a=>1}
>> hash.to_s
=> "b2c3d4a1"

RUBY_VERSION => 1.9.1

>> hash = {:a=> 1, :b=>2, :c=>3, :d=>4}
=> {:a=>1, :b=>2, :c=>3, :d=>4}
>> hash.to_s
=> "{:a=>1, :b=>2, :c=>3, :d=>4}"

hash.each and hash.each_pair

RUBY_VERSION => 1.8.6

>> hash = {:a=> 1, :b=>2, :c=>3, :d=>4}
=> {:b=>2, :c=>3, :d=>4, :a=>1}
>> hash.each{|x| p x}
[:b, 2]
[:c, 3]
[:d, 4]
[:a, 1]
=> {:b=>2, :c=>3, :d=>4, :a=>1}
>> hash.each_pair{|x| p x}
(irb):48: warning: multiple values for a block parameter (2 for 1)
        from (irb):48
[:b, 2]
(irb):48: warning: multiple values for a block parameter (2 for 1)
        from (irb):48
[:c, 3]
(irb):48: warning: multiple values for a block parameter (2 for 1)
        from (irb):48
[:d, 4]
(irb):48: warning: multiple values for a block parameter (2 for 1)
        from (irb):48
[:a, 1]
=> {:b=>2, :c=>3, :d=>4, :a=>1}

RUBY_VERSION => 1.9.1

>> hash = {:a=> 1, :b=>2, :c=>3, :d=>4}
=> {:a=>1, :b=>2, :c=>3, :d=>4}
>> hash.each{|x| p x}
[:a, 1]
[:b, 2]
[:c, 3]
[:d, 4]
=> {:a=>1, :b=>2, :c=>3, :d=>4}
>> hash.each_pair{|x| p x}
[:a, 1]
[:b, 2]
[:c, 3]
[:d, 4]
=> {:a=>1, :b=>2, :c=>3, :d=>4}

hash.select now returns hash instead of array

RUBY_VERSION => 1.8.6

>> hash = {:a=> 1, :b=>2, :c=>3, :d=>4}
=> {:b=>2, :c=>3, :d=>4, :a=>1}
>> hash.select{|k,v| k == :c }
=> [[:c, 3]]

RUBY_VERSION => 1.9.1

>> hash = {:a=> 1, :b=>2, :c=>3, :d=>4}
=> {:a=>1, :b=>2, :c=>3, :d=>4}
>>  hash.select{|k,v| k == :c }
=> {:c=>3}

Leave a Reply

Your email address will not be published. Required fields are marked *