A method that returns the hash key as an array
key method
languages = { japan: 'Japanese', us: 'English', india: 'Hindi' }
languages.keys #=>[:japan, :us, :india]
A method that returns the hash value as an array
values method
languages = { japan: 'Japanese', us: 'English', india: 'Hindi' }
languages.values #=> ["Japanese", "Enlgish", "Hindi"]
A method to check if the specified key exists in the hash
has_key?
languages = { japan: 'Japanese', us: 'English', india: 'Hindi' }
languages.has_key?(:japan) #=> true
languages.has_key?(:italy) #=> false
Prefix a hash with ** to expand the keys and values of other hashes within the hash literal
**
h = { us: 'English', india: 'Hindi' }
{ japan: 'Japanese', **h } #=> {japan: 'Japanese', us: 'English', india: 'Hindi'}
#The same effect can be obtained by using the merge method.
{ japan: 'Japanese'}.merge(h) #=> {japan: 'Japanese', us: 'English', india: 'Hindi'}
A method to convert a hash to an array using the to_a method
to_a
languages = { japan: 'Japanese', us: 'English', india: 'Hindi' }
languages.to_a #=> [[:japan, "Japanese"], [:us, "English"], [:india, "Hindi"]]
A method that can convert an array to a hash
to_h
array = [[:japan, "Japanese"], [:us, "English"], [:india, "Hindi"]]
array.to_h #=> {:japan=>"Japanese", :us=>"English", :india=>"Hindi"}
#To for an array that cannot be parsed as a hash_An error occurs when calling the h method
array = [5, 6, 7, 8]
array.to_h #=> TypeError: wrong element type Integer at 0 (expected array)
#Unexpected error when duplicate keys
array = [[:japan, "Japanese"], [:japan, "Japanese"]]
array.to_h #=> {:japan=>"Japanese"}
It can also be converted to an array by passing it to Hash []
Hash[]
array = [[:japan, "Japanese"], [:us, "English"], [:india, "Hindi"]]
Hash[array] #=> {:japan=>"Japanese", :us=>"English", :india=>"Hindi"}
python
h = Hash.new('OK')
a = h[:aaa] #=> "ok"
b = h[:bbb] #=> "ok"
#Variable a and b are the same object
a.equal?(b) #=> true
#If you make a destructive change to variable a, the value of variable b will change with it.
a.upcase!
a #=> "OK"
b #=> "OK"
Use blocks
h = Hash.new{'OK'}
a = h[:aaa] #=> "ok"
b = h[:bbb] #=> "ok"
#Variable a and b are different objects
a.equal?(b) #=> false
#Applying destructive changes to variable a does not change the value of variable b
a.upcase!
a #=> "OK"
b #=> "ok"
References An introduction to Ruby for those who want to become professionals
Recommended Posts