if

An if evaluates the given branch if its condition is truthy. Otherwise, it
evaluates the else branch if present.

  1. a = 1
  2. if a > 0
  3. a = 10
  4. end
  5. a #=> 10
  6. b = 1
  7. if b > 2
  8. b = 10
  9. else
  10. b = 20
  11. end
  12. b #=> 20

To write a chain of if-else-if you use elsif:

  1. if some_condition
  2. do_something
  3. elsif some_other_condition
  4. do_something_else
  5. else
  6. do_that
  7. end

After an if, a variable’s type depends on the type of the expressions used in both branches.

  1. a = 1
  2. if some_condition
  3. a = "hello"
  4. else
  5. a = true
  6. end
  7. # a : String | Bool
  8. b = 1
  9. if some_condition
  10. b = "hello"
  11. end
  12. # b : Int32 | String
  13. if some_condition
  14. c = 1
  15. else
  16. c = "hello"
  17. end
  18. # c : Int32 | String
  19. if some_condition
  20. d = 1
  21. end
  22. # d : Int32 | Nil

Note that if a variable is declared inside one of the branches but not in the other one, at the end of the if it will also contain the Nil type.

Inside an if‘s branch the type of a variable is the one it got assigned in that branch, or the one that it had before the branch if it was not reassigned:

  1. a = 1
  2. if some_condition
  3. a = "hello"
  4. # a : String
  5. a.size
  6. end
  7. # a : String | Int32

That is, a variable’s type is the type of the last expression(s) assigned to it.

If one of the branches never reaches past the end of an if, like in the case of a return, next, break or raise, that type is not considered at the end of the if:

  1. if some_condition
  2. e = 1
  3. else
  4. e = "hello"
  5. # e : String
  6. return
  7. end
  8. # e : Int32