When inside of a method in Ruby, what is the difference between print
and return
?
def squared_number(num)
return (num**2)
end
and
def squared_number(num)
print (num**2)
end
When inside of a method in Ruby, what is the difference between print
and return
?
def squared_number(num)
return (num**2)
end
and
def squared_number(num)
print (num**2)
end
A lot.
print
will output the number without a newline on the end.
return
will return the number from the method.
return
ends current method returning passed parameter as a result. Example:
def add(a, b)
return a + b
end
c = add(1, 2)
In Ruby last statement returns value automatically. So we can define our add
method like this
def add(a, b)
a + b
end
But return
is very useful, if you want to end a method execution prior to the last line. For example:
def specialAdd(a, b)
if a < 0
return -1
end
a + b
end
This method returns always -1 if the first argument is negative. In all other cases it works just like add
method.
On the other hand the print
method outputs the passed parameter to the standard output (console) returning nil
as a result. We can see it using irb
- interactive ruby console:
$ irb
irb(main):002:0> print "Hello World\n"
Hello World
=> nil
irb(main):003:0>
Here we see "Hello World"
plus newline printed. The returned value of the print method is nil
.