Ruby: how to combine puts and return inside if condition?

Viewed 2303

How can I print a message and then return from a function in ruby?

2.3.4 :038 > def foo(num)
2.3.4 :039?>   print "Your number is: #{num}" && return if num > 10
2.3.4 :040?>   print "Number too small"
2.3.4 :041?>   end
 => :foo
2.3.4 :042 > foo(47)
 => nil
2.3.4 :043 > foo(7)
Number too small => nil
2.3.4 :044 >

When I called foo with 47 why didn't I got Your number is: 47 in output?

PS: This function can be written in other simpler ways also, I just wanted to express my doubt via this function.

6 Answers

Since print (and puts) returns nil, this works just as well:

def foo(num)
  return print "Your number is: #{num}" if num > 10
  print "Number too small"
end

And to show clearer intention, place the guard clause first:

def foo(num)
  return print "Number too small" if num <= 10
  print "Your number is: #{num}"
end

Examples:

> foo 47
Your number is: 47=> nil
> foo 7
Number too small=> nil
Related