Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Examples of a module, class and singleton class in Ruby
class MultipleInstancesOfState
attr_accessor :state
def initialize(state:)
@state = state
end
def foo
@state.reverse!
end
end
an_instance = MultipleInstancesOfState.new(state: 'wombat')
an_instance.foo
#=> "tabmow"
another_instance = MultipleInstancesOfState.new(state: 'wombat')
another_instance.foo
#=> "tabmow"
module NoState
module_function
def foo(bar:)
bar.reverse
end
end
NoState.foo(bar: 'wombat')
#=> "tabmow"
NoState.foo(bar: 'tabmow')
#=> "wombat"
require 'singleton'
class SingleInstanceOfState
include Singleton
attr_accessor :state
def initialize
@state = nil
end
def foo
@state.reverse!
end
end
singleton_instance = SingleInstanceOfState.instance
singleton_instance.state = 'wombat'
singleton_instance.foo
#=> "tabmow"
SingleInstanceOfState.instance.foo
#=> "wombat"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment