LoginSignup
0
2

More than 3 years have passed since last update.

【Ruby】any?メソッドの使い方

Posted at

個人メモです。

any?メソッドを使うことで、対象のオブジェクトの中に該当する要素が一つでもあればtrueを返す

オブジェクト.any?{ |変数| 条件式 }



ブロック{}を省略した場合は、対象のオブジェクトの中に値が存在すればtrueを返す

オブジェクト.any?


ブロックありの場合

▼trueの事例

true1
arr = [1, 2, 3]

arr.any?{|x| x < 2}
=> true

▼falseの事例

false1
arr = [1, 2, 3]

arr.any?{|x| x > 10}
=> false


ブロックなしの場合

▼trueの事例

true1
arr = [1, 2, 3]

arr.any?
=> true
true2
arr = [nil, 2, nil]

arr.any?
=> true



▼falseの事例

false1
arr3 = []

arr3.any?
=> false
false2
arr4 = [nil, nil, nil]

arr4.any?
=> false
0
2
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
0
2