Search code examples
ruby-on-railsrubyfunctionreturn

What is Returned in Ruby if the Last Statement Evaluated is an If Statement


My understanding is that ruby returns the last statement evaluated in a function. What if the function ends with an if statement that evaluates to false

def thing(input)
  item = input == "hi"
  if item
    []
  end
end

puts thing("hi").class #> Array
puts thing("not hi").class #> NilClass

I like this functionality (returning nil if the statement is false), but why isn't false returned (from the assignment to item)?


Solution

  • If your if statement doesn't result in any code being run, it returns nil, otherwise it returns the value of the code that was run. irb is a good tool to experiment with such stuff:

    irb(main):001:0> i = if false then end
    => nil
    irb(main):002:0> i = if true then end
    => nil
    irb(main):007:0> i = if false then "a" end
    => nil
    irb(main):008:0> i = if false then "a" else "b" end
    => "b"