Skip to content

Instantly share code, notes, and snippets.

@cheeyeo
Created May 7, 2014 16:10
Show Gist options
  • Save cheeyeo/cefb04a8dfed1b922e9b to your computer and use it in GitHub Desktop.
Save cheeyeo/cefb04a8dfed1b922e9b to your computer and use it in GitHub Desktop.
Defining idempotent conversion functions
def Point(*args)
respond_to_point = ->(arg){ arg.respond_to?(:to_point) }
respond_to_ary = -> (arg){ arg.respond_to?(:to_ary) }
case args.first
when Integer then Point.new(*args)
when String then Point.new(*args.first.split(':').map(&:to_i))
when respond_to_point
args.first.to_point
when respond_to_ary
Point.new(*args.first.to_ary)
else
raise TypeError, "Cannot convert #{args.inspect} to Point"
end
end
Point = Struct.new(:x, :y) do
def inspect
"#{x}:#{y}"
end
def to_point
self
end
end
Pair = Struct.new(:a,:b) do
def to_ary
[a, b]
end
end
class Flag
def initialize(x,y,flag_color)
@x, @y, @flag_color = x, y, flag_color
end
def to_point
Point.new(@x,@y)
end
end
p Point([5,7])
p Point(Pair.new(23,32))
p Point(Flag.new(42,24,:red))
@cheeyeo
Copy link
Author

cheeyeo commented May 7, 2014

Example from the Confident Ruby book

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment