1
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?

More than 3 years have passed since last update.

Ruby ハッシュについて(続)

Last updated at Posted at 2020-06-04

前回のハッシュに関する記事

ハッシュの同値比較

== でハッシュ同士を比較すると、同じハッシュかどうかをチェックできます。
このときすべてのキーと値が同じであれば、trueが返ります。
たとえ並び順が異なっていたとしても、キーと値がすべて同じであれば、trueとなります。

(例)

x = { 'a' => 1, 'b' => 2, 'c' => 3}
y = { 'b' => 2, 'c' => 3, 'a' => 1}
x == y # => true

要素数の取得

sizeメソッド(= length)を使うと、ハッシュの要素の個数を調べることができます。

{ 'a' => 1, 'b' => 2, 'c' => 3 }.size # => 3

要素の削除

deleteメソッドで指定したキーに対応する要素を削除できます。
最後に、ハッシュを出力させると、要素が削除されていることがわかります。

menus = { 'food' => 'rice', 'drink' => 'water', 'dessert' => 'cake' }
menus.delete('food') # => "rice" 削除された要素の値が戻り値となります
puts menus                             # => {"drink" => "water", "dessert" => "cake"}

参考にした文献

プロを目指す人のためのRuby入門

1
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
1
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?