我已经设置了以下任务并继续得到标题中提到的错误,但无法弄清楚原因。任何帮助都会很棒。
# Given a sentence, return an array containing every other word.
# Punctuation is not part of the word unless it is a contraction.
# In order to not have to write an actual language parser, there won't be any punctuation too complex.
# There will be no "'" that is not part of a contraction.
# Assume each of these charactsrs are not to be considered: ! @ $ # % ^ & * ( ) - = _ + [ ] : ; , . / < > ? \ |
#
# Examples
# alternate_words("Lorem ipsum dolor sit amet.") # => ["Lorem", "dolor", "amet"]
# alternate_words("Can't we all get along?") # => ["Can't", "all", "along"]
# alternate_words("Elementary, my dear Watson!") # => ["Elementary", "dear"]
def alternate_words(string)
no_p = string.gsub(/[^a-z ^A-Z ^0-9 ']/)
new_words = []
no_p.split.each.with_index {|x,i| new_words << string[i] if i.even? }
new_words
end
答案 0 :(得分:1)
no_p = string.gsub(/[^a-z ^A-Z ^0-9 ']/)
您没有正确使用gsub
。什么是替代字符?见http://ruby-doc.org/core-2.1.4/String.html#method-i-gsub。如果您没有提供替换,那么gsub将返回一个Enumerator对象。
答案 1 :(得分:0)
String.gsub仅在传递一个参数时返回枚举器。您需要为该方法指定替换或块以返回String。 split
是String上的方法,而不是Enumerator上的方法,因此是您的错误。