[RUBY] Hash

How to take out the key

h = {"apple" => "red"}

h.keys #=> ["apple"]

h.keys[0] # => "apple"

flatten (flattening a multidimensional array)

a = [1, [2, [3, [4, 5]]]]

a.flatten(1) #=> [1, 2, [3, [4, 5]]]
a.flatten(2) #=> [1, 2, 3, [4, 5]]
a.flatten(3) #=> [1, 2, 3, 4, 5]
a.flatten    #=> [1, 2, 3, 4, 5]

merge (hash merge)

h1 = {"red" => "apple"}
h2 = {"red" => "tomato"}
h1.merge(h2) #=> {"red"=>"tomato"}
h2.merge(h1) #=> {"red"=>"apple"}

As above, if the keys are the same, they will be overwritten by the hash value of the argument. merge can receive blocks as shown below, and can specify the behavior when the key is duplicated.

h1 = {"red" => "apple"}
h2 = {"red" => "tomato"}
h1.merge(h2){|key,h1v,h2v| "#{h1v}" + "," + "#{h2v}"}
#=> {"red"=>"apple,tomato"}

key ?, has_key? (Check for the existence of the key)

h = {"red" => "apple"}
h.key?("red")     #=> true
h.has_key?("red") #=> true

h.key?("blue")    #=> false
h.has_key?("blue")#=> false

Recommended Posts

hash
Hash
Hash basics
Ruby Hash notes
[Ruby] Hash retrieval
[About double hash]
[ruby] Double hash
Ruby double hash
[Rails] Introducing Active Hash
Utilization of Active Hash
Explaining Ruby's Hash object
hash and each statement
Pitfalls of Active Hash