Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why would .is_a? and .class give conflicting results?

Tags:

ruby

I have three objects that are all the same class. One was created via Item.new and the other two were pulled from the database (Mongoid). I'm passing one/any of these objects to another method and checking the type in that method via is_a?:

def initialize (item, attrs = nil, options = nil)
  super(attrs, options)
  raise 'invalid item object' unless item.is_a?(Item)

Well, this raise is getting hit. So I check the class, is_a and instance_of in rails console. I'm getting conflicting results. Why would they have the same class but only one of them be an instance_of that class?

>> i0.is_a? Item
=> false
>> i1.is_a? Item
=> false
>> i2.is_a? Item
=> true

>> i0.class
=> Item
>> i1.class
=> Item
>> i2.class
=> Item

>> i0.instance_of?(Item)
=> false
>> i1.instance_of?(Item)
=> false
>> i2.instance_of?(Item)
=> true

Is there a better way to do this type checking of my inputs? Why would three things that are the same class not all be instances of that class?

like image 414
jcollum Avatar asked Feb 06 '12 16:02

jcollum


People also ask

What is IS_A in Ruby?

The is_a? method will return a true value if an object is a of the type given as a parameter OR if it inherits from the type given as a parameter. So in effect, you can use it to ask "is there going to be a method from a class which I can run on this object".

Is number in Ruby?

In Ruby, Integers are object of class Fixnum(32 or 64 bits) or Bignum(used for bigger numbers). Floating-point numbers: Numbers with decimal points are usually called floats, e.g., 1.2, 10.0. The floating-point numbers are object of class Float.


1 Answers

I don't know Mongoid, but usually, in a DB access library, you don't get the actual object out of the database but rather a proxy object that acts as a stand-in for the object stored in the DB. Since Ruby lacks the features to implement a perfect transparent proxy, you will sometimes see odd results, especially when using reflection or around object identity.

like image 132
Jörg W Mittag Avatar answered Sep 27 '22 17:09

Jörg W Mittag