Skip to content

Instantly share code, notes, and snippets.

@yowchun93
Created March 30, 2020 01:30
Show Gist options
  • Save yowchun93/7ec7b0645214065cbe1fa8547c55c4fb to your computer and use it in GitHub Desktop.
Save yowchun93/7ec7b0645214065cbe1fa8547c55c4fb to your computer and use it in GitHub Desktop.
Strategy Pattern
class TextParser
attr_reader :text, :parser
def initialize(text, parser)
@text = text
@parser = parser
end
def call
parser.call(text)
end
end
class XMLParser
def call(text)
"<text>#{text}</text>"
end
end
class JSONParser
def call(text)
"{ text: #{text} }"
end
end
puts TextParser.new('My Text', XMLParser.new).call
puts TextParser.new('My Text', JSONParser.new).call
# -> (text) { text.reverse } is a reference to a lambda. This demonstrates
# the power of functional programming.
puts TextParser.new('My Text', -> (text) { text.reverse }).call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment