Last active
March 11, 2022 17:51
-
-
Save havenwood/a81401724cbcbf1f78e79f42ed4b0e33 to your computer and use it in GitHub Desktop.
Examples of a module, class and singleton class 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
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" |
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
module NoState | |
module_function | |
def foo(stateless:) | |
stateless.reverse | |
end | |
end | |
NoState.foo(stateless: 'wombat') | |
#=> "tabmow" | |
NoState.foo(stateless: 'tabmow') | |
#=> "wombat" |
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
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