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 this
>
> def scribble color.new
>      color = Color.lookup ???
>      ....
> end
>
>
That'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
  end

  def scribble color
    color = Color.lookup color
    ...
  end

This 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/