If I declare @var in Ruby, every object of that class would have its own @var. 
But what if I miss @? I mean, I declare a variable called var2 without @. Do they share the variable or it is temporarily created? 
When variable is declared without scope prefix (@ - instance, @@ - class or $ - global) then is declared for current scope, i.e:
class Foo
  def boo
    @boo ||= 'some value'
    var ||= 40
    puts "boo: #@boo var: #{var}"
  end
  def foo
    var ||= 50
    puts "boo: #@boo var: #{var}"
  end
end
c = Foo.new
c.boo # => boo: some value var: 40
c.foo # => boo: some value var: 50
def foo
  $var ||= 30
  puts "$var: #$var"
end
foo # => $var: 30
puts "$var: #$var" # => $var: 30
%w[some words].each do |word|
  lol = word # blocks introduce new scope
end
puts lol # => NameError: undefined local variable or method `lol'
for word in %w[some words]
  lol = word # but for loop not
end
puts lol # => words
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With