7
1

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 1 year has passed since last update.

Array と Parameters の `select!` について

Last updated at Posted at 2022-03-10

Array#select!Parameters#select! の返り値が違う

  • Array の方は,ブロックの返り値の全部が true を返した場合に nilを返している
    • 変化が無いので self を返さないとのこと
  • ActionController::Parameters の方は,最後に self を強制的に返すようになっている

普通はひっかからないと思うけど,これに依存したコードを書くのは良くなさそうなので,一応記す.
select! を使わないだろう.の意

Refs

a = %w{ a b c d e f }
a.select! {|v| v =~ /[a-z]/ }   # => nil
a # => ["a", "b", "c", "d", "e", "f"]

Equivalent to Hash#keep_if, but returns nil if no changes were made.

    def select!(&block)
      @parameters.select!(&block)
      self
    end

keep_if は常に self を返します。 filter! と select! はオブジェクトが変更された場合に self を、されていない場合に nil を返します。

7
1
3

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?