Last active
June 1, 2020 15:02
-
-
Save choonkeat/9815130 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
condition = false | |
puts "hello" if condition | |
#=> nil | |
# note there is no printing of `hello`, this means `conditions` was evaluated first before performing the preceding code | |
# this is expected and expanding the preceding code into `begin...end` yields you the same result | |
condition = false | |
begin | |
puts "hello" | |
end if condition | |
#=> nil | |
# note there is no printing of `hello`, this means `condition` was evaluated first before trying to evaluate `begin..end` | |
# | |
# | |
# | |
# | |
# now let's try `while` instead of `if` | |
n = 3 | |
(n -= 1).tap {|x| puts "# code: #{x}" } while n.tap {|x| puts "# condition: #{x}" } > 0 | |
# condition: 3 | |
# code: 2 | |
# condition: 2 | |
# code: 1 | |
# condition: 1 | |
# code: 0 | |
# condition: 0 | |
# => nil | |
# note that condition was evaluated first (thus printed first). so this is consistent with the behavior of `code if condition` construct | |
# | |
# BUT if we expand code to `begin..end` | |
n = 3 | |
begin | |
(n -= 1).tap {|x| puts "# code: #{x}" } | |
end while n.tap {|x| puts "# condition: #{x}" } > 0 | |
# code: 2 | |
# condition: 2 | |
# code: 1 | |
# condition: 1 | |
# code: 0 | |
# condition: 0 | |
=> nil | |
# note that `begin...end` code is evaluated before `condition`. | |
# though this "looks like what other languages do", ruby is unfortunately inconsistent with itself. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment