2013-11-27 7 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, чтобы найти спички вместо:

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

Поскольку пользователь соответствует словам, шаблон должен дублировать это. Само по себе регулярное выражение соответствует подстроке, а не совпадению слов. Выделите шаблон с помощью '\ b', чтобы сделать его совпадением слов:'/\ bfoo \ b'. Поскольку поисковая строка не требуется разделять, поиск на основе регулярного выражения может быть очень быстрым. –

Смежные вопросы