Don't confuse the function definition and the thing that calls the
function. If you had my definition above, you could then call:
scribble Color.new(...)
scribble :black
scribble 'white'
scribble Color.lookup('black')
but not:
scribble 42
scribble Array.new
etc.
···
On 3 June 2014 16:01, Roelof Wobben <r.wobben@home.nl> wrote:
Matthew Kerwin schreef op 3-6-2014 7:44:
On 3 June 2014 15:13, Roelof Wobben <r.wobben@home.nl> wrote:
Matthew Kerwin schreef op 3-6-2014 2:10:
A more Ruby way might be to have Color.lookup(color) be perfectly
happy to accept a Color object. Then you'd have:def scribble color
color = Color.lookup color
...
end For comparison, see Kernel#Integer and friends.
thanks,
But what if someone does thisdef scribble color.new
color = Color.lookup ???
....
endThat's not valid Ruby code, I don't know what you're trying to represent
there. But this is what I was thinking:class Color
@@names = {
black: Color.new(0,0,0),
white: Color.new(255,255,255),
}
def Color.lookup c
case c
when Color
c
when Symbol, String
if @@names[c.to_sym]
@@names[c.to_sym]
else
raise ArgumentError, "Not a color nane"
end
else
raise ArgumentError, "can't convert #{c.class.name} into Color"
end
end
enddef scribble color
color = Color.lookup color
...
endThis is the opposite of duck-typing, it's effectively doing type
casting. If you call Color.lookup with a Color object, you get it back
unmodified. If you call it with no parameters, you get a generic Ruby
"ArgumentError: wrong number of arguments (0 for 1)" error.
--
Matthew Kerwin
http://matthew.kerwin.net.au/Then Im confused by this test-case :
Test.assert_equals is_santa_clausable(SantaClaus.new), true
Roelof
--
Matthew Kerwin
http://matthew.kerwin.net.au/