我有一个数组
array = ["this","is","a","sentence"]
如果array
中的一个单词与我正在寻找的单词匹配,我想打印一个字符串。
示例:
array = ["this","is","a","sentence"]
array.each { |s|
if
s == "sentence"
puts "you typed the word sentence."
elsif
s == "paragraph"
puts "You typed the word paragraph."
else
puts "You typed neither the words sentence or paragraph."
end
此方法将打印:
"You typed neither the words sentence or paragraph."
"You typed neither the words sentence or paragraph."
"You typed neither the words sentence or paragraph."
"you typed the word sentence."
我希望它识别单词"sentence"
并执行"you typed the word sentence."
。如果其中一个单词不存在,它将执行else语句"you typed neither the words sentence or paragraph."
。
答案 0 :(得分:4)
您需要使用include?
检查数组:
array = ["this","is","a","sentence"]
if array.include?("sentence")
puts "You typed the word sentence."
elsif array.include?("paragraph")
puts "You typed the word paragraph."
else
puts "You typed neither the words sentence or paragraph."
end
1.9.3p448 :016 > array = ["this","is","a","sentence"]
=> ["this", "is", "a", "sentence"]
1.9.3p448 :017 >
1.9.3p448 :018 > if array.include?("sentence")
1.9.3p448 :019?> puts "You typed the word sentence."
1.9.3p448 :020?> elsif array.include?("paragraph")
1.9.3p448 :021?> puts "You typed the word paragraph."
1.9.3p448 :022?> else
1.9.3p448 :023 > puts "You typed neither of the words sentence or paragraph."
1.9.3p448 :024?> end
You typed the word sentence.
答案 1 :(得分:4)
使这看起来很棘手的基本问题是,你将找到单词(循环遍历数组)的行为与你想要做的行为结合在一起找到了。
更为惯用的方法是将它们分开:
array = ["this","is","a","sentence"]
found = array.find {|word| word == 'sentence' || word == 'paragraph' }
case found
when 'sentence' then puts 'You typed the word sentence'
when 'paragraph' then puts 'You typed the word paragraph'
else puts "You typed neither the words sentence or paragraph"
end
答案 2 :(得分:1)
好像你正在拆分用户的输入。您可以使用regular expressions来查找匹配项:
input = "this is a sentence"
case input
when /sentence/
puts "You typed the word sentence"
when /paragraph/
puts "You typed the word paragraph"
else
puts "You typed neither the words sentence or paragraph"
end
正如TheTinMan所指出的,你必须用\b
(匹配字边界)来包围模式,以匹配整个单词:
/sentence/ === "unsentenced" #=> true
/\bsentence\b/ === "unsentenced" #=> false
/\bsentence\b/ === "sentence" #=> true