Ruby Ruby Basics Ruby Syntax Method Return Values

valeriuv
valeriuv
15,596 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!

2 Answers

valeriuv
valeriuv
15,596 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
Lukasz Walczak
Lukasz Walczak
6,619 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