[英]Iterating over an array in ruby
我有一个数组
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."
。
您要使用include?
检查数组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.
使这个看上去很棘手的基本问题是,您将发现单词的操作(遍历数组)与找到单词后要执行的操作结合在一起。
一种更惯用的写法将它们分开:
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
似乎您正在拆分用户的输入。 您可以使用正则表达式来查找匹配项:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.