我必須寫一個名為consonant_cancel的方法,它接收一個句子并回傳一個新的句子,其中每個詞都以它的第一個元音開始。給定的測驗函式的預期輸出是 puts consonant_cancel("down the rabbit hole") #=> "own e abbit ole"
puts consonant_cancel("writing code is challenging") #=> "iting ode is allenging"
但我得到的是"own e abbit it ole e""iting ing ode e is allenging enging"與這個代碼
def consonant_cancel(stence)
arr = []
元音='aeiou'
詞 = 句子.分割
words.each do | words|
word.each_char.with_index do |char, i|
if vowels.include? (char)
arr << word[i..-1]
end
end] end
end end
return arr.join(' '/span>)
end
puts consonant_cancel("down the rabbit hole") #=> "own e abbit ole"
puts consonant_cancel("writing code is challenging") #=> "iting ode is allenging"。
你們能幫我除錯一下嗎。
uj5u.com熱心網友回復:
如果我們加入一個puts來看看你的回圈中發生了什么:
def consonant_cancel(句子)
arr = []
元音='aeiou'
詞 = 句子.分割
words.each do | words|
word.each_char.with_index do |char, i|
if vowels.include?(char)
將char
arr << word[i..-1]
end
end] end
end end
return arr.join(' '/span>)
結束
然后運行consonant_cancel "hello world",我們看到:
irb(main):044:0>consonant_cancel "hello world"
e
o
o
=>"ello o orld"
irb(main):045:0>
你會在任何有多個輔音的單詞中看到同樣的問題,因為你在一個單詞中回圈使用字符并檢查輔音的方式。
一個更簡單的方法是使用正則運算式來完成這個任務。
words.split.map { |w| w.sub(/^[^aeiou]*/i, " ) }.join(' ')
uj5u.com熱心網友回復:
word.each_char.with_index
這個回圈遍歷了該詞的所有字符(和元音)。在發現第一個元音后斷開,因此它不會對這個詞的后續元音重復產生副作用。
作為一個替代方案,這里有另一個基于regex的解決方案
def consonant_cancel(stence)
sentence.scan(/[^aeiou]*(. ?)/i).join(" ")
end。
uj5u.com熱心網友回復:
你可以使用String#gsub與一個正則運算式。不需要將字串分成幾塊進行處理和隨后的重新組合。
def consonant_cancel(str)<
str.gsub(/(?<![a-z])[a-z&&[^aeiou]] /i,' ')
end。
consonant_cancel("down the rabbit hole" )
#=> "own e abbit ole"
輔音_cancel("寫代碼很有挑戰性")
#=> "iting ode is allenging"。
關于Regexp的檔案中的 "字符類 "部分,以獲得對&&運算子的解釋。
我們可以用自由間隔模式1來寫正則運算式,以使其具有自我記錄功能。
//
(?<! # 開始一個負面的lookbehind。
[a-z] # 匹配一個小寫字母!
) # End negative lookbehind[/span]。
[a-z&&[^aeiou]] # 匹配一個或多個元音以外的小寫字母 。
/ix # Invoke case-indifference and free-spacing mode
負的lookahead確保沒有任何緊挨著的字母串被匹配。該行
[a-z&& [^aeiou]]
也可以寫成
[b-df-hj-np-tv-z]
1. 請參閱檔案中的 "自由間隔模式和注釋 "一節,以了解Regexp。
uj5u.com熱心網友回復:
你不需要寫這么大的編碼。你可以寫下面的代碼來完成你想要的東西。
輸入
a="down the rabbit hole"。
代碼
p a.split
.map { |x| x.sub(/[^aeiou]/, ""/span>) }
.join(" ")
輸出
"own he abbit ole"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/323812.html
標籤:
上一篇:在Ruby中壓縮2個以上的變數
