Skip to content

Instantly share code, notes, and snippets.

@choonkeat
Last active June 1, 2020 15:02
Show Gist options
  • Save choonkeat/9815130 to your computer and use it in GitHub Desktop.
Save choonkeat/9815130 to your computer and use it in GitHub Desktop.
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