0

I'm trying to split a string to capitalize each word.

Code:

def titleize(a)
little_words = %w(a an the)
#a = %w(a quick brown fox jumps) --> works if an array is specifically used.
a.split(" ")
a.each do |i|
    if !little_words.include? "#{i}"
    i.capitalize!
    end
end
g = a.join(" ")
return g
end

print titleize("a quick brown fox jump")

Error:

  `titleize': undefined method `each' for "a quick brown fox jump":String (NoMethodError)

However, I am running into this error. From what I understand, the error is saying that my variable 'a' is a string which does not contain the method 'each'. I have already applied 'split(" ")' to convert the string to an array. Why does it not work?

1
  • You use the split but you don't store the resulting array anywhere. "a" is still a string which doesn't have an "each" method. Commented Jul 4, 2017 at 8:15

1 Answer 1

2

Because you are ignoring what the method returns

a = a.split(" ")

And " " is the default for split so you can write simply

a = a.split
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. I understand the ruby has certain methods such as "i.to_s" which converts an integer to string without having to deal with a return. Is there any equivalent for split?
to_s returns a string but don't modify the object on which is called. It's the same. There are some methods that modify object in-place but they return the same "type", in this case split is called on a string and returns an array, is not possible
@axiac ! is only a convention, there are several methods without ! that modify the receiver. I think more important is the fact that an object can't change its identity. A string can modify itself, i.e. its characters, but it can't turn itself into an array or an integer. A string will always be a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.