Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby variables' visibility

Tags:

ruby

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?

like image 401
OneZero Avatar asked Dec 21 '22 09:12

OneZero


1 Answers

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
like image 174
Hauleth Avatar answered Dec 31 '22 18:12

Hauleth