Skip to content

Instantly share code, notes, and snippets.

@mlanett
Created December 12, 2014 22:44
Show Gist options
  • Save mlanett/3536d28b25f2db42fb90 to your computer and use it in GitHub Desktop.
Save mlanett/3536d28b25f2db42fb90 to your computer and use it in GitHub Desktop.
Singleton fields in Ruby
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