Created
May 7, 2014 16:10
-
-
Save cheeyeo/cefb04a8dfed1b922e9b to your computer and use it in GitHub Desktop.
Defining idempotent conversion functions
This file contains hidden or 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
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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example from the Confident Ruby book