One of the first files I looked at, lib/shoes.rb, opens right up with this interesting bit of interestingness:
class RangeOkay. So we're defining a
def rand
conv = (Integer === self.end && Integer === self.begin
? :to_i
: :to_f)
((Kernel.rand * (self.end - self.begin))
+ self.begin).send(conv)
end
end
rand()
method on the built-in Ruby class Range
, which will return a random value from within the begin
and end
values of the Range
. Neato. And apparently the use of conv
is meant to produce a result of a float or an integer, depending on the nature of the endpoints of the Range
. Again: neato. But I hadn't seen the use of the ===
operator in this context before. The docs and the Pickaxe book are a little obtuse on this, so I did some
irb
spelunking:>> r = (1..27)Hmm. So
=> 1..27
>> r.class
=> Range
>> r.begin
=> 1
>> r.begin.instance_of? Integer
=> false
>> r.begin.class
=> Fixnum
>> r.begin.kind_of? Fixnum
=> true
>> r.begin.kind_of? Integer
=> true
instance_of()
doesn't mean quite the same in Ruby as, say, the instanceof
operator in Java does. (That, or Fixnum
doesn't truly inherit from Integer
in Ruby.)Also, as it turns out:
>> Fixnum === r.beginSo it would seem that the
=> true
>> Integer === r.begin
=> true
[class] === [value]
syntax is syntactic sugar for [value].kind_of? [class]
It's the bit about:
>> r.begin.instance_of? Integerthat surprised me most, being the pathetic Java programmer that I am. And being that (according to the documentation for Integer on ruby-doc.org):
=> false
Apparently "is the basis for" != "is a superclass of".Integer
is the basis for the two concrete classes that hold
whole numbers,Bignum
andFixnum
.
Or is that "!==="...?