Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active March 11, 2022 17:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save havenwood/a81401724cbcbf1f78e79f42ed4b0e33 to your computer and use it in GitHub Desktop.
Save havenwood/a81401724cbcbf1f78e79f42ed4b0e33 to your computer and use it in GitHub Desktop.
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"
an_instance.foo
#=> "wombat"
another_instance = MultipleInstancesOfState.new(state: 'corge')
another_instance.foo
#=> "egroc"
module NoState
module_function
def foo(stateless:)
stateless.reverse
end
end
NoState.foo(stateless: 'wombat')
#=> "tabmow"
NoState.foo(stateless: '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"
singleton_instance.foo
#=> "wombat"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment