LoginSignup
1
1

More than 3 years have passed since last update.

[Ruby]includes?メソッドを使って配列内の要素を調べる

Posted at

配列の中に特定の文字列が含まれていたら、切り出して別の処理をしたい。

includes?メソッド

include?メソッドは指定した要素が、配列中に含まれているかを判定するメソッド

array = ["foo", "bar"]
puts array.include?("bar")
#=> true
puts array.include?("hoge")
#=> false

問題例

配列内に特定の文字が入っていたら「true」、それ以外の文字であれば「false」と返すメソッドを作る。


ここでは特定の文字は1,2,3の数字とする。
コードを書いていく。

def array123(nums)
  if nums.include?(1) && nums.include?(2) && nums.include?(3)
    puts "True"
  else
    puts "False"
  end
end

今回呼び出すのはarray123のメソッドとし、numsを仮引数にしておき、実引数を受け取る準備はOK。

def array123(nums)



if条件分岐を用いて1,2,3のそれぞれが含まれていたら以下の処理をしてねとしてあげる。
論理演算子&&(〜との意味)や||(もしくはの意味)などを用いる。

if nums.include?(1) && nums.include?(2) && nums.include?(3)

trueのときにさせたい処理があればif~elseの間に記述、
falseのときにさせたい処理があればelse~endの間に記述する。


■参考リファレンス
* https://docs.ruby-lang.org/ja/latest/method/Array/i/include=3f.html

1
1
2

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
1