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

前端 未结 5 1222
一向
一向 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:50

    The only time that I like to use then on a multi-line if/else (yes, I know it's not required) is when there are multiple conditions for the if, like so:

    if some_thing? ||
      (some_other_thing? && this_thing_too?) ||
      or_even_this_thing_right_here?
    then
      some_record.do_something_awesome!
    end
    

    I find it to be much more readable than either of these (completely valid) options:

    if some_thing? || (some_other_thing? && this_thing_too?) || or_even_this_thing_right_here?
      some_record.do_something_awesome!
    end
    
    # or
    
    if some_thing? ||
      (some_other_thing? && this_thing_too?) ||
      or_even_this_thing_right_here?
      some_record.do_something_awesome!
    end
    

    Because it provides a visual delineation between the condition(s) of the if and the block to execute if the condition(s) evaluates to true.

提交回复
热议问题