我想通過數組搜索一個具體項目:搜索在陣列
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