Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 312
Tyler DeWitt Avatar asked Aug 21 '12 19:08

Tyler DeWitt


People also ask

Does Ruby have return statement?

Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it. If you wanted to explicitly return a value you can use the return keyword.

What does a Ruby function return by default?

Ruby has implicit returns. This means that if a return is the last expression in a path of execution, there's no need for the return keyword. Worth noting is that return 's default argument is nil , which is a falsey value.

Does if need end in Ruby?

Ruby tries to get close to English syntax this way. The end is just necessary to end the block, while in the second version, the block is already closed with the if.

What is the syntax of Ruby if else statement?

Ruby if else if statement tests the condition. The if block statement is executed if condition is true otherwise else block statement is executed. Syntax: if(condition1)


2 Answers

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"
like image 70
theglauber Avatar answered Sep 30 '22 07:09

theglauber


The return value is the value of the if expression is the value of the clause that was evaluated and not of the condition. In case no clause was evaluated (if without else), nil is returned:

irb(main):001:0> x = if false
irb(main):002:1> []
irb(main):003:1> end
=> nil
irb(main):004:0> x
=> nil
irb(main):005:0>
like image 34
davidrac Avatar answered Sep 30 '22 07:09

davidrac