I will make a note of the basic methods that can be used with Ruby hashes.
** values_at ** Returns an array of values corresponding to multiple specified keys
menu
=> {"Udon"=>"400 yen", "Soba"=>"350 yen", "ramen"=>"700 yen"}
menu.values_at("Udon","Soba","ramen")
=> ["400 yen", "350 yen", "700 yen"]
Returns nil
if there is no corresponding key
menu
=> {"Udon"=>"400 yen", "Soba"=>"350 yen", "ramen"=>"700 yen"}
menu.values_at("Udon","Soba","ramen","Hoto")
=> ["400 yen", "350 yen", "700 yen", nil]
** fetch ** Get the value of the specified key
menu
=> {"Udon"=>"400 yen", "Soba"=>"350 yen", "ramen"=>"700 yen"}
menu.fetch("Udon")
=> "400 yen"
menu.fetch("Soba")
=> "350 yen"
(KeyError) if the key cannot be found
menu
=> {"Udon"=>"400 yen", "Soba"=>"350 yen", "ramen"=>"700 yen"}
irb(main):025:0> menu.fetch("Hoto")
Traceback (most recent call last):
.
.
.
KeyError (key not found: "Hoto")
** invert ** Swap keys and values and return a new hash
menu
=> {"Udon"=>"400 yen", "Soba"=>"350 yen", "ramen"=>"700 yen"}
menu.invert
=> {"400 yen"=>"Udon", "350 yen"=>"Soba", "700 yen"=>"ramen"}
** merge ** merge hashes
menu
=> {"Udon"=>"400 yen", "Soba"=>"350 yen", "ramen"=>"700 yen"}
menu2
=> {"tea"=>"150 yen", "Cola"=>"300 yen"}
menu.merge(menu2)
=> {"Udon"=>"400 yen", "Soba"=>"350 yen", "ramen"=>"700 yen", "tea"=>"150 yen", "Cola"=>"300 yen"}
** store ** Add an element to the hash
menu
=> {"Udon"=>"400 yen", "Soba"=>"350 yen", "ramen"=>"700 yen"}
menu.store("Hoto","600 yen")
=> "600 yen"
menu
=> {"Udon"=>"400 yen", "Soba"=>"350 yen", "ramen"=>"700 yen", "Hoto"=>"600 yen"}
** select ** Pass the key and value in the hash to the block in order, collect the elements for which the block returned true
, and return a new hash
test
=> {"Oishi"=>80, "moat"=>45, "Tanaka"=>60, "Takano"=>25}
test.select {|key,value| value >= 50}
=> {"Oishi"=>80, "Tanaka"=>60}
** reject ** Pass the key and value in the hash to the block in order, collect the elements that the block returned false
, and return a new hash
test
=> {"Oishi"=>80, "moat"=>45, "Tanaka"=>60, "Takano"=>25}
irb(main):053:0> test.reject {|key,value| value >= 50}
=> {"moat"=>45, "Takano"=>25}
Recommended Posts