Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
chrisstanda
277 PointsHow can one write a function in ruby that takes a string and outputs the number of words contained in the string?
def WordCount(str)
# code goes here
return str
end
# keep this function call here
# to see how to enter arguments in Ruby scroll down
WordCount(STDIN.gets)
1 Answer
Andrew Kiernan
26,892 PointsHi Chris!
Any time I'm asked to count words in a string, I usually break the string into an array and get the length of that. You can use the ruby #split method and pass in an empty space, like this "Testing string splitting".split(' '). Make sure you put a space between the quotes in the split method (otherwise it splits after every character). Then find the length of that array, and that should be the number of words in the string!
Hope that helps!
-Andrew