Skip to content

Instantly share code, notes, and snippets.

@benhamill
Created March 23, 2012 03:25
Show Gist options
  • Save benhamill/2166460 to your computer and use it in GitHub Desktop.
Save benhamill/2166460 to your computer and use it in GitHub Desktop.
How do all those variable-types work in different scopes?
class Foo
def self.bar
@bar ||= :self_bar
end
def self.bar=(b)
@bar = b
end
def bar
@bar ||= :instance_bar
end
def bar=(b)
@bar = b
end
def self.baz
@@baz ||= :self_baz
end
def self.baz=(b)
@@baz = b
end
def baz
@@baz ||= :instance_baz
end
def baz=(b)
@@baz = b
end
end
class Bing < Foo
end

Class Instance Variables

Foo.bar
# => :self_bar

Bing.bar
# => :self_bar

Foo.bar = 'non-default value'
Foo.bar
# => 'non-default value'

Bing.bar
# => :self_bar

Instance Variables

f1 = Foo.new
f2 = Foo.new
b  = Bing.new

f1.bar
# => :instance_bar

f2.bar
# => :instance_bar

b.bar
# => :instance_bar

f1.bar = 'non-default value'
f1.bar
# => 'non-default value'

f2.bar
# => :instance_bar

b.bar
# => :instance_bar

Class Class Variables (?!?)

Foo.baz
# => :self_baz

Bing.baz
# => :self_baz

Foo.baz = 'non-default value'
Foo.baz
# => 'non-default value'

Bing.baz
# => 'non-default value'

Class Variables

f1 = Foo.new
f2 = Foo.new
b  = Bing.new

f1.baz
# => :instance_baz

f2.baz
# => :instance_baz

b.baz
# => :instance_baz

f1.baz = 'non-default value'
f1.baz
# => 'non-default value'

f2.baz
# => 'non-default value'

b.baz
# => 'non-default value'
@nyarly
Copy link

nyarly commented Mar 23, 2012

I'd add a couple of variations (although it quickly becomes a combinatorial issue, and maybe to a limited benefit):

module Broda
def broda
# @Broda, @@Broda
end
end

and then:
class Foo
include Broda
extend Brode
end

class Bing
include Brodi
extend Brodo
end

f1 = Foo.new
f1.extend Brodu
etc.

@nyarly
Copy link

nyarly commented Mar 23, 2012

There's also this variation

Foo.class_eval
def broda
end
end

(as well as instance_eval, which, iirc, has slightly different semantics on a class than class_eval)

And
f1.instance_eval do
def self.broda; end
end

@nyarly
Copy link

nyarly commented Mar 23, 2012

Really, the details of inheritance and access in Ruby are worth exploring. I sometimes think a template or a gem or something would be helpful - just not sure how.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment