Last active
August 18, 2016 16:16
-
-
Save JoshCheek/14e126acce58f843b598 to your computer and use it in GitHub Desktop.
Examples of Ruby hoisting variables
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
# generic hoisting | |
if true | |
a = 1 | |
end | |
a # => 1 | |
begin | |
b = 2 | |
end | |
b # => 2 | |
for whatevz in [1, 2] | |
c = 3 | |
end | |
c # => 3 | |
# multi-level hoisting | |
if true | |
if true | |
if true | |
d = 4 | |
end | |
end | |
end | |
d # => 4 | |
if false | |
if false | |
if false | |
e = 5 | |
end | |
end | |
end | |
e # => nil | |
# Ruby's multiline if statement hoists, but its inline one doesn't, inconsistent enough to seem like a bug: | |
if f = 'F' | |
f # => "F" | |
end | |
f # => "F" | |
g if g = 'B' # => NameError: undefined local variable or method `g' for main:Object | |
# ~> NameError | |
# ~> undefined local variable or method `g' for main:Object | |
# ~> | |
# ~> /var/folders/7g/mbft22555w3_2nqs_h1kbglw0000gn/T/seeing_is_believing_temp_dir20150323-47469-1c0cwrl/program.rb:47:in `<main>' |
Yeah, this is different than JavaScript hoisting (confusing nonetheless).
Also, let me increase confusion by a little bit :)
g if g = 'B' # => NameError: undefined local variable or method `g' for main:Object
g # => "B"
# or, in a .rb file rather than irb/pry
begin
g if g = 'B'
rescue => e
p g # => "B"
raise e
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i total agree with you @baldwindavid