Qiita Conference 2025 Autumn

特別ゲスト12名登壇!! (敬称略)

piacere, 牛尾 剛, 和田 卓人, seya, ミノ駆動, Esteban Suarez, 市谷 聡啓, からあげ, 岩瀬 義昌, まつもとゆきひろ, みのるん, Null-Sensei

197
172

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 5 years have passed since last update.

ActiveSupportのHash拡張であるslice, exceptがびっくりするぐらい便利

Posted at

ActiveSupportによる既存Rubyクラスの拡張は人間をダメにするんじゃないかと思いますが、知っていると周りのプログラマに差をつけられるテクニックが満載だと思います。今回はHashの拡張メソッドの話。

よくあるコード

some_hash = {
  key_a: "some content",
  key_b: "some content",
  key_c: "some content"
}

# :key_aと:key_bを取り出したい
some_hash.select{|k, _| %i(key_a key_b).include? k} #=> {key_a: ..., key_b: ...}

# :key_cを除外したい
some_hash.reject{|k, _| k == :key_c} #=> {key_a: ..., key_b: ...}

いちいち「取り出したい」「除外したい」だけなのにブロックを使うのもおおげさな感じがします。

ActiveSupport拡張を使うと・・・

some_hash = {
  key_a: "some content",
  key_b: "some content",
  key_c: "some content"
}

# :key_aと:key_bを取り出したい
some_hash.slice(:key_a, :key_b) #=> {key_a: ..., key_b: ...}

# :key_cを除外したい
some_hash.except(:key_c) #=> {key_a: ..., key_b: ...}

こんなにシンプルに書けちゃいます。!をつけると破壊的なメソッドになります。

その他の便利メソッド

compact

hash = { a: true, b: false, c: nil }
hash.compact # => { a: true, b: false }
hash # => { a: true, b: false, c: nil }

reverse_merge

options = options.reverse_merge(size: 25, velocity: 10)
# 以下のコードと等価
options = { size: 25, velocity: 10 }.merge(options)

以上、知っていると便利なActiveSupportによるHash拡張のご紹介でした。

197
172
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

Qiita Conference 2025 Autumn will be held!: 11/5(Wed) - 11/7(Fri)

Qiita Conference is Qiita's largest tech conference, dedicated to engineers in the age of AI!

Keynote Speaker

piacere, Tsuyoshi Ushio, Esteban Suarez, Takuto Wada, seya, MinoDriven, Toshihiro Ichitani, Karaage, Yoshimasa Iwase, Matz, Minorun, Null-Sensei

View event details

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

197
172

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?