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

Ruby Ruby Basics (Retired) Ruby Methods Method Returns: Part 2

Matthew Stanciu
Matthew Stanciu
4,222 Points

"Make sure you return a nicely formatted string", but the string is formatted

I keep getting an error on this challenge telling me to make sure my method returns a nicely formatted string, but it does return a formatted string. I tried the code I ran in a workspace and it returned 'The remainder of 100 divided by 2 is 0. ' I don't understand what I am doing wrong.

method.rb
def mod(a,b)
  puts "The remainder of #{a} divided by #{b} is #{a%b}."
end
mod(100,2)

1 Answer

andren
andren
28,558 Points

Your code prints a nicely formatted string, it does not return it. This is an extremely common misconception among beginners, printing something (with puts for example) and returning something are two very different things. They only appear to behave somewhat similarly when you are doing very simple tasks, and when using the ruby REPL for simple examples.

To return something you have to either use the keyword return, like this:

def mod(a,b)
  return "The remainder of #{a} divided by #{b} is #{a%b}."
end

Or make use of a Ruby feature called "implicit return" where Ruby automatically returns whatever value is located in the last statement of your method, which would look like this in this case:

def mod(a,b)
  "The remainder of #{a} divided by #{b} is #{a%b}."
end

Getting into exactly what return does vs puts is a bit difficult without getting into more complex code examples and concepts. But in essence you are returning the value to the code that called the method, rather than simply printing the value to the screen. It's something that will start to make more sense on as you get further into the course, and start to see practical examples of return being used.