Created
December 12, 2014 22:44
-
-
Save mlanett/3536d28b25f2db42fb90 to your computer and use it in GitHub Desktop.
Singleton fields in Ruby
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
def assert condition | |
raise unless condition | |
end | |
# | |
# @fields at the class level are singleton fields. | |
# Singleton fields may be initialized but this is not required. | |
# Singleton fields can only be accessed by singleton methods. | |
# Singleton fields are not inherited by subclasses (although singleton methods *are* inherited). | |
# | |
class Singleton | |
@field = 1 | |
def self.field | |
@field | |
end | |
def self.field=(f) | |
@field = f | |
end | |
end | |
class DerivedSingleton < Singleton | |
# does not inherit @field | |
end | |
assert Singleton.field == 1 | |
Singleton.field = 2 | |
assert Singleton.field == 2 | |
assert DerivedSingleton.field == nil | |
DerivedSingleton.field = 1 | |
assert Singleton.field == 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment