Reputation: 1395
Given
def sayMoo numberOfMoos
puts 'mooooooo...'*numberOfMoos
'yellow submarine'
end
I am having trouble understanding why
x = sayMoo 2
puts x
gives me
mooooooo...mooooooo...
yellow submarine
and
sayMoo 2
gives me
mooooooo...mooooooo...
I am hoping someone could explain it.
Upvotes: 0
Views: 48
Reputation: 44715
puts
is a method displaying given string (or object) to console (by default). Your method is calling it to display 'moooo... mooo', and then returns the result of lastly excuted expression, in this case it returns the string 'yellow submarine'. Hence when you do:
x = sayMoo 2
You are executing your method, which first displays 'moo' message, and then assign 'yallow submarine' to variable x, which you can use puts
on to display. If you just do:
sayMoo 2
method is executed, but the value returned by method is lost and is not being displayed.
Upvotes: 0
Reputation: 78561
Calling the functionputs
moooooos.
The first example puts
the function's return value, which is yellow submarine, in addition to that.
The second, in contrast, just calls the function.
Upvotes: 2