3

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
jvperrin
  • 3,368
  • 1
  • 23
  • 33
Abulurd
  • 1,018
  • 4
  • 15
  • 31
  • related: http://stackoverflow.com/questions/5018633/what-is-the-difference-between-print-and-puts – Francisco Corrales Morales Mar 06 '14 at 23:17
  • also related: http://stackoverflow.com/questions/21821074/returning-a-string-from-a-ruby-function – edwardsmatt Mar 06 '14 at 23:19
  • FYI: Ruby methods return the last line, in that case `return` is not necessary. – cortex Mar 06 '14 at 23:20
  • 1
    `print` and `return` have entirely different functions in the language. One outputs to the console or a file stream, and the other changes program flow and optionally returns a value. `return` never outputs to the console or a file stream. – the Tin Man Mar 06 '14 at 23:50
  • Think of it this way: the `print` method is for telling _humans_ something; the `return` statement is for telling _the rest of the program_ the result of a method call. – Phrogz Mar 07 '14 at 15:31

2 Answers2

5

A lot.

print will output the number without a newline on the end.

return will return the number from the method.

Blue Ice
  • 7,888
  • 6
  • 32
  • 52
5

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.

Boris Brodski
  • 8,425
  • 4
  • 40
  • 55