Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Last active August 18, 2016 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/14e126acce58f843b598 to your computer and use it in GitHub Desktop.
Save JoshCheek/14e126acce58f843b598 to your computer and use it in GitHub Desktop.
Examples of Ruby hoisting variables
# 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>'
@baldwindavid
Copy link

Sorry to randomly pick out this gist, but was comparing differences in variable assignment behavior between Javascript and Ruby and stumbled upon this. I have seen it named hoisting in a few different places. That seems like a bit of a misnomer but I might just be misunderstanding. I mean, it is not hoisting the variable assignment anywhere is it? If any of those variables were called prior to the assignment with the conditionals, they would be unassigned. However, in javascript, you could call those variables prior to the conditional and they would be actually moved up and available there. Clearly Ruby has a thing they are doing here, but I guess I'm thinking that maybe hoisting is not the exact name for it. No?

@sushantbajra
Copy link

I have to agree with @baldwindavid.

@omokehinde
Copy link

i total agree with you @baldwindavid

@halilim
Copy link

halilim commented Aug 18, 2016

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