1

In this example:

def hello
  puts "hi"
end

def hello
  "hi"
end

What's the difference between the first and second functions?

3 Answers 3

10

In Ruby functions, when a return value is not explicitly defined, a function will return the last statement it evaluates. If only a print statement is evaluated, the function will return nil.

Thus, the following prints the string hi and returns nil:

puts "hi"

In contrast, the following returns the string hi:

"hi"

Consider the following:

def print_string
  print "bar"
end

def return_string
  "qux" # same as `return "qux"`
end

foo = print_string
foo #=> nil

baz = return_string
baz #=> "qux"

Note, however, that you can print and return something out of the same function:

def return_and_print
  print "printing"
  "returning" # Same as `return "returning"`
end

The above will print the string printing, but return the string returning.

Remember that you can always explicitly define a return value:

def hello
  print "Someone says hello" # Printed, but not returned
  "Hi there!"                # Evaluated, but not returned
  return "Goodbye"           # Explicitly returned
  "Go away"                  # Not evaluated since function has already returned and exited
end

hello
#=> "Goodbye"

So, in sum, if you want to print something out of a function, say, to the console/log – use print. If you want to return that thing out of the function, don't just print it – ensure that it is returned, either explicitly or by default.

Sign up to request clarification or add additional context in comments.

1 Comment

Good stuff. Very thorough. @zeantsoi
1

The first one uses the puts method to write "hi" out to the console and returns nil

the second one returns the string "hi" and doesn't print it

Here's an example in an irb session:

2.0.0p247 :001 > def hello
2.0.0p247 :002?>   puts "hi"
2.0.0p247 :003?> end
 => nil 
2.0.0p247 :004 > hello
hi
 => nil 
2.0.0p247 :005 > def hello
2.0.0p247 :006?>   "hi"
2.0.0p247 :007?> end
 => nil 
2.0.0p247 :008 > hello
 => "hi"
2.0.0p247 :009 > 

Comments

0

puts prints it to the console. So

def world
  puts 'a'
  puts 'b'
  puts 'c'
end

Will print 'a' then 'b' then 'c' to the console.

def world
  'a'
  'b'
  'c'
end

This will return the last thing, so you will only see 'c'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.