Skip to content

Instantly share code, notes, and snippets.

@eterps
Created October 29, 2015 13:42
Show Gist options
  • Save eterps/5751c38dba1dbe00565d to your computer and use it in GitHub Desktop.
Save eterps/5751c38dba1dbe00565d to your computer and use it in GitHub Desktop.
Ruby conversion functions pattern
# From Confident Ruby, page 72
module Graphics
module Conversions
module_function
def Point(*args)
case args.first
when Point then args.first
when Array then Point.new(*args.first)
when Integer then Point.new(*args)
when String then Point.new(*args.first.split(':').map(&:to_i))
else
raise TypeError, "Cannot convert #{args.inspect} to Point"
end
end
end
Point = Struct.new(:x, :y) do
def inspect
"#{x}:#{y}"
end
end
end
Graphics::Conversions::Point(3, 5) # => 3:5
include Graphics
include Graphics::Conversions
Point(Point.new(2, 3)) # => 2:3
Point([9, 7]) # => 9:7
Point(3, 5) # => 3:5
Point('8:10') # => 8:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment