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?

[Ruby] Hash#delete でキーが存在しない場合に KeyError を発生させる

Last updated at Posted at 2025-07-03

やりたいこと

Hash#delete を使用して Hash オブジェクトから特定の要素を取り除く。その際、指定したキーが存在しない場合に KeyError を発生させたい。そのような場合、Hash#delete は通常 nil を返す。

方法

Hash#delete にブロックを渡し、ブロックの中で KeyError を発生させる。指定したキーが存在しない場合のみに評価される。

hash = { cat: '🐈', dog: '🐕' }

hash.delete(:cat)
#=> "🐈"
hash
#=> {dog: "🐕"}
hash.delete(:cat)
#=> nil

hash = { cat: '🐈', dog: '🐕' }

hash.delete(:cat) { |key| raise(KeyError, key: key) }
#=> "🐈"
hash
#=> {dog: "🐕"}
hash.delete(:cat) { |key| raise(KeyError, key: key) }
# {key: :cat} (KeyError)

hash = { cat: nil, dog: '🐕' }
#=> {cat: nil, dog: "🐕"}

# キーに対応する値が nil の場合、キーは存在するので KeyError は発生しない。
hash.delete(:cat) { |key| raise(KeyError, key: key) }
#=> nil
hash
#=> {dog: "🐕"}
hash.delete(:cat) { |key| raise(KeyError, key: key) }
# {key: :cat} (KeyError)

バージョン情報

$ ruby -v
ruby 3.4.4 (2025-05-14 revision a38531fd3f) +PRISM [arm64-darwin24]
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?