-1

配列があるとします

["70 percent chance of rain", " 35 percent chance of snow"]

を含む要素のインデックスを取得するにはどうすればよい"rain"ですか?

4

1 に答える 1

4

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
于 2013-05-30T10:54:30.710 に答える