What is the difference between “if” statements with “then” at the end?

前端 未结 5 1229
一向
一向 2020-12-03 04:27

What\'s the difference between these two Ruby if statements when we put a then at the end of the if statement?

if(val          


        
5条回答
  •  臣服心动
    2020-12-03 04:59

    Here's a quick tip that is not directly related to your question: in Ruby, there is no such thing as an if statement. In fact, in Ruby, there are no statements at all. Everything is an expression. An if expression returns the value of the last expression that was evaluated in the branch that was taken.

    So, there is no need to write

    if condition
      foo(something)
    else
      foo(something_else)
    end
    

    This would better be written as

    foo(
      if condition
        something
      else
        something_else
      end
    )
    

    Or as a one-liner

    foo(if condition then something else something_else end)
    

    In your example:

    something.meth(if val == 'hi' then 'hello' else 'right' end)
    

    Note: Ruby also has a ternary operator (condition ? then_branch : else_branch) but that is completely unnecessary and should be avoided. The only reason why the ternary operator is needed in languages like C is because in C if is a statement and thus cannot return a value. You need the ternary operator, because it is an expression and is the only way to return a value from a conditional. But in Ruby, if is already an expression, so there is really no need for a ternary operator.

提交回复
热议问题