1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ハッシュ(hash)

Last updated at Posted at 2020-08-11

#keyの取り出し方

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

h.keys #=> ["apple"]

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

#flatten(多次元配列の平坦化)

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(ハッシュの結合)

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

上のように、キーが同じ場合、引数のハッシュの値で上書きされてしまう。
mergeは下のようにブロックを受け取ることができ、キーが重複した時の挙動を指定することができる。

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

#key? , has_key?(キーの存在を確かめる)

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

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?