Tuesday, 11 November 2014

Hashes in Ruby:

hash= Hash.new


puts hash[0].nil?     #returns true..

h2= Hash.new("default Value")

puts h2["key1"]  #returns default value..

h3= Hash.new
h3={'k1'=>'val1', 'k2'=> 'v2'}
puts h3.size
puts h3.inspect
puts h3.keys.inspect
puts h3['k2']


h4= Hash['a'=> 'apple', "b"=> 'bat']
puts h4


h5= Hash.new("Default")
arr1= [1,2,3,4]
arr2=['x','y','z','p']
for i in 0..arr1.size
h5[arr1[i]]=arr2[i]
end

puts '+++++++++++Using conditions+++++++++++++++++++'
puts h5.inspect
puts h5[4] unless h5[4].nil?
puts h5[4] if ! h5[4].nil?
puts h5[4] if not h5[4].nil?

h= Hash.new
h[1]='a'
puts h.inspect


For Hash related methods, refer: http://www.tutorialspoint.com/ruby/ruby_hashes.htm

No comments:

Post a Comment