簡體   English   中英

在Ruby中遍歷數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM