Reputation:
Ive bee set the following task and keep getting the error mentioned in the title but cant figure out why. Any help would be great.
# 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
Upvotes: 0
Views: 332
Reputation: 17958
String.gsub returns an Enumerator when passed only a single argument. You need to specify a replacement or block for that method to return a String. split
is a method on String, not on Enumerator, hence your error.
Upvotes: 0
Reputation: 1272
no_p = string.gsub(/[^a-z ^A-Z ^0-9 ']/)
you are not using gsub
correctly. What are the replacement chars? See http://ruby-doc.org/core-2.1.4/String.html#method-i-gsub. If you do not provide a replacement then gsub returns an Enumerator object.
Upvotes: 1