我想通过数组搜索一个具体项目:搜索在阵列
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
我想通过数组搜索一个具体项目:搜索在阵列
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
if letters.index('b')
puts "yes"
else
puts "no"
end
有一个在建造方法,这样做:
letters.include? "b"
尝试: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
letters.select {| l | l =='a'} – crackedmind 2014-09-26 08:52:14
'如果letters.include?(“b”)',请阅读[documentation](http://www.ruby-doc.org/core-2.1.3/Array.html# class-Array-label-Obtaining + Information + about + an + Array) – Stefan 2014-09-26 08:54:16
@crackedmind这在'if语句'中不起作用。它会始终通过,因为它会返回至少一个空数组。 '如果letters.select {| l | l =='a'} .count> 0;提出“是的,一个在那里”;我相信这是一个更好的解决方案。但@斯蒂芬的解决方案应该是被接受的答案。 – Webdevotion 2014-09-26 08:55:45