Editing Topic: RCR218 Project: RCR | RCRchive home

RCR 218: kind_of class'es

submitted by neoneye on Thu Feb 19 2004 04:01:18 PM -0800

Status: pending


Abstract

Let #kind_of? take multiple arguments.

Problem

Its not visible at first sight, when this method will raise. If the number of classes to check is 3 or more, then its even more difficult.
def push(choice)
  unless choice.kind_of?(Zero) or choice.kind_of?(One)
    raise ArgumentError, "got #{choice.class}"
  end
  @choices << choice
end

Proposal

Now its much easier to tell when this method raises an exception.
def push(choice)
  unless choice.kind_of?(Zero, One)
    raise ArgumentError, "got #{choice.class}"
  end
  @choices << choice
end

Analysis

For consistency it probably also necessary to do the same with instance_of?.

Implementation

class Object
  alias old_kind_of kind_of?
  def kind_of?( *classes )
    classes.each{|cl| return true if old_kind_of(cl) }
    false
  end
end

p 3.kind_of?(String)          # false
p 3.kind_of?(String, Fixnum)  # true


Back to RCRchive.


RCR Submission page and RCRchive powered by Ruby, Apache, RuWiki (modified), and RubLog