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

Bryson Massey
Bryson Massey
1,047 Points

I'm having trouble getting the remainder of two arguments returned into a string. Any help?

def mod (a, b) puts "Dividing #{a} by #{b}" return a % b end

method.rb
def mod(a, b)
  puts "Dividing #{a} and #{b}"
  return a % b 
  a = a
  b = b
  c = a % b
  string = " The remainder of #{a} % by #{b} is #{c}"
  puts string
end

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

You have a bit of unnecessary code here. There's no reason to set a to a and b to b. But besides that, remember that a function will stop running the second it hits the first return statement. So you're sending back the remainder and not the string. But then you continue on and try to print a string. The challenge specifically says to return the string... not print it. Also the string itself requires a period at the end or the challenge will fail. Try this out:

def mod(a, b)
  c = a % b
  return "The remainder of #{a} divided by #{b} is #{c}."
end
Bryson Massey
Bryson Massey
1,047 Points

Thank you, I was overthinking it and wasn't paying attention. Now that I read it, it makes sense.

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Jennifer is spot on :smiley:. You could also eliminate the c variable all together and do the calculation in the string interpolation itself.

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

That's what I love about code ... so many different, yet right, ways of doing the same thing!

:dizzy:

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Jason Anders Agreed! I sort of assumed that line wouldn't work because the instructions specifically stated to use c. And you know how challenges can be :) But your code is more elegant and passes the test, of course!

Jason Anders
Jason Anders
Treehouse Moderator 145,860 Points

You're right Jennifer Nordell. Those darn challenges. Lol. :)

When I first read the challenge, I thought it was giving an 'example' of what it wanted. But, now I see it does specifically ask for the c variable. So, you're code is more correct for the challenge, and I'm actually now surprised my example does pass. Hmm? :confused: