配列があるとします
["70 percent chance of rain", " 35 percent chance of snow"]
を含む要素のインデックスを取得するにはどうすればよい"rain"
ですか?
index
メソッドを使用する必要があります
array = ["70 percent chance of rain", " 35 percent chance of snow"]
index = array.index { |x| x.include?('rain') } # gives 0
index = array.index { |x| x.include?('snow') } # gives 1
注:-これにより、文字列が最初に出現したインデックスが得られ、文字列が存在しない場合は返されますnil
for ex:- percent
は両方の配列要素に存在するため、返されます0
index = array.index { |x| x.include?('percent') } # gives 0
「存在しない」はどの要素にも存在しないため、返されますnil
index = array.index { |x| x.include?('not present') } # gives nil