0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Ruby初学者】RubyのHashクラスを学ぶ

Posted at

【Ruby初学者】Hashクラスの基本まとめ(自分用メモ)

Rubyの Hash クラスについて、IRBで確認しながら学んだことを自分用にまとめたものです。
特に「これは何だっけ?」となりやすい member?, to_a, update, clear の挙動を確認していきます。


member? でハッシュがキーをもつか判断できる

Hash#member?key?has_key? の別名。

h = {a: 1, b: 2}
h.member?(:a)  # => true
h.member?(:z)  # => false

to_aでハッシュから配列を生成できる

Hash#to_aは、ハッシュを[[:key, value], [:key, value]]の形の配列に変換できる。

h = {a: 1, b: 2}
h.to_a  # => [[:a, 1], [:b, 2]]

updateは破壊的メソッドである

Hash#updatemerge!の別名で、元のハッシュを直接書き換える(破壊的)。

h = {a: 1}
h.update({b: 2})  # => {:a=>1, :b=>2}
# h は変更されている

clearの戻り値は空のハッシュ

Hash#clearはハッシュの中身をすべて消して、空のハッシュ {} を返します。

h = {a: 1}
h.clear  # => {}

まとめ

  • member? でキーが存在するかチェックできる
  • to_a で配列に変換できる
  • update は破壊的(元のハッシュが書き換わる)
  • clear は中身を削除し、空のハッシュを返す

Rubysilverの取得を目指してます。
がんばります。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?