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 Ruby Syntax Method Return Values

valeriuv
valeriuv
20,999 Points

I am not sure if I missed it, but Jay does not explain why the call to puts is returning that empty value?

Why did the call to puts at 9:16 return an empty value? Jay just said it did, but did not explain why.

Thanks!

3 Answers

valeriuv
valeriuv
20,999 Points

I think I get it now: is it because the method put does not return a value in general, so there is no value to be assigned to the variable number? So the correct way would have been not to use puts in the content of the subtract method, right?

Jay McGavren
Jay McGavren
Treehouse Teacher

That's right. The puts method returns nil, which is a value that represents the absence of a value. (A little confusing, I know, but that is what it means.) You can see the nil value for yourself by running:

p(puts("hello"))

So yes, you want:

def subtract(first, second)
  first - second
end

...and NOT:

def subtract(first, second)
  puts first - second # Returns nil!
end

So the value of the 'number' is nil.. but it still runs and prints the method? which is why we see 8 printed out still??

Lukasz Walczak
Lukasz Walczak
6,620 Points
number = 9
puts number
number = subtract(number,1) # value of the 'number' should be nil, not 8 imho
puts number # prints 8 to the console
puts number.class # class is nil

so if the variable 'number' is nil why will it still print a value (8 in this case) to the terminal? if nil is absence of the value, where the value is coming from then?

Jay McGavren
Jay McGavren
Treehouse Teacher

What I'm observing does not match what you are observing... Here are two snippets that include two different definitions for the subtract method, to help avoid confusion. I'm also using the p method instead of puts, because p can show nil values.

Here it is returning the result of the math operation:

def subtract(first, second)
  first - second
end

number = 9
p number # prints 9 to the console
number = subtract(number,1)
p number # prints 8 to the console
p number.class # class is Integer

And here it is returning nil because puts was used within subtract (which you should not do):

def subtract(first, second)
  puts first - second
end

number = 9
p number # prints 9 to the console
number = subtract(number,1) # value of the 'number' IS nil
p number # prints "nil"
p number.class # class is NilClass