7
3

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.

Hash の値が空文字のキーを除去したい

7
Last updated at Posted at 2017-11-06

ActiveSupport の Hash#compact は 値が nil のものしか除去してくれない。 例えば、
Rack::Utils.parse_query などの戻り値から値が空文字のものを除去したいときに、ど忘れするのでメモしておく。

> { a: 1,  b: "" , c: " ",  d: nil, e: true, f: false }.transform_values(&:presence).compact
=> {:a=>1, :b=>"", :c=>" ", :e=>true, :f=>false}

Hash#compactHash#transform_values は元々 ActiveSupport にあったメソッドで、 Ruby 2.4 で追加されたメソッド。 Object#presence は Ruby 本体にはなく、 ActiveSupport の拡張。

7
3
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?