搜索数组中的特定项

时间:2014-09-26 08:50:33

标签: ruby

我想搜索数组:

letters = ["a", "b", "c", "d", "e"]

查看"b"是否在其中;如果是,那么应该说是。我明白了:

letters[0..0] == ["a"]

我试过了:

if letters[0..5] == ["b"]
  puts "Yes, the letter 'b' in there."
else
  puts "No 'b' in the array."
end

3 个答案:

答案 0 :(得分:4)

有一种内置方法可以做到这一点:

letters.include? "b"

答案 1 :(得分:2)

尝试:http://www.ruby-doc.org/core-2.1.3/Array.html#method-i-include-3F

if letters.include?("b")
  puts "Yes, the letter 'b' in there."
else
  puts "No 'b' in the array."
end

答案 2 :(得分:0)

if letters.index('b')
    puts "yes"
else
    puts "no"
end