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

Jose Ramirez
Jose Ramirez
9,946 Points

how to write a method returned the remainder in a nice full sentence?

I am having problems in writing a nice full sentence when writing the code using methods.

method.rb
def mod(a, b)
  #write your code here
  puts "The remainder of a divided by b is c "
  return a % b
end
puts mod(2,2)

3 Answers

Allison Hanna
Allison Hanna
36,222 Points

Hi Jose,

Instead of using puts, we want to use return in order to return the string. Additionally, we can actually create the variable c as a%b. The body of the method should start with creating that c variable, then returning that nicely formatted sentence.

Does that help?

Christos Peramatzis
Christos Peramatzis
16,428 Points

I am not fairly sure what you're trying to accomplish with your method.

In case you want to print the sentence you have in your method, here's how you could do it.

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

Then, by calling it, you'd get the following

mod(2,2)
The remainder of 2 divided by 2 is 0
=> nil

That version of the method would print the sentence and return nothing.

In your example, you are returning the result. If for some reason you want to save the value, you could do the following

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

And this could be called as

result = mod(2,2)
The remainder of 2 divided by 2 is 0
=>0

This way, the result of a % b could be held in the variable result, for later use.

If you don't know about string interpolation (the #{} in the strings), you should watch the Ruby Basics video

Jose Ramirez
Jose Ramirez
9,946 Points

Thank you you are a life saver. Greetings from California!