2013-11-27 89 views
0

數組我有遍歷紅寶石

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."

回答

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 
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

好像你已經分裂了用戶的輸入。你可以使用regular expressions找到匹配,而不是:

/sentence/  === "unsentenced" #=> true 
/\bsentence\b/ === "unsentenced" #=> false 
/\bsentence\b/ === "sentence" #=> true 

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以全字匹配(匹配單詞邊界

+1

由於用戶匹配的單詞,該模式需要重複。自己的正則表達式是子字符串匹配,而不是單詞匹配。用'\ b'環繞模式使其成爲單詞匹配:'/ \ bfoo \ b'。由於搜索字符串不必拆分,基於正則表達式的搜索可能非常快。 –