This post originated from an RSS feed registered with Ruby Buzz
by Jay Fields.
Original Post: Ruby: === operator
Feed Title: Jay Fields Thoughts
Feed URL: http://feeds.feedburner.com/jayfields/mjKQ
Feed Description: Blog about Ruby, Agile, Testing and other topics related to software development.
Recently I was looking at creating a patch for Mocha that would allow you to specify a class as an argument. The feature was added to allow you to specify that an argument can be any instance of the class specified.
object.expects(:do_this).with(Fixnum, true, 99) object.do_this(2, true, 99) # satisfies the expectation
To support this new feature I looked into the === method.
The === method of Object is defined as:
Case Equality���For class Object, effectively the same as calling #==, but typically overridden by descendents to provide meaningful semantics in case statements.
There's no mystery here, use === like ==. However, the === method of Module provides the behavior I'm looking for.
Case Equality���Returns true if anObject is an instance of mod or one of mod���s descendents. Of limited use for modules, but can be used in case statements to classify objects by class.
The documentation can be tested easily to ensure the behavior I'm looking for.
Fixnum === 2 #=> true
An important thing to note is that 2 and Fixnum are not commutative.
2 === Fixnum #=> false
So, using the === method I was able create the following patch that provides the behavior I was looking for.