88

In Java, you can do instanceof. Is there a Ruby equivalent?

steenslag
  • 79,051
  • 16
  • 138
  • 171
NullVoxPopuli
  • 61,906
  • 73
  • 206
  • 352

5 Answers5

171

It's almost exactly the same. You can use Object's instance_of? method:

"a".instance_of? String # => true
"a".instance_of? Object # => false

Ruby also has the is_a? and kind_of? methods (these 2 are aliases, and work exactly the same), which returns true is one of the superclasses matches:

"a".is_a? String # => true
"a".is_a? Object # => true
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
John Topley
  • 113,588
  • 46
  • 195
  • 237
  • 1
    N.B. As far as I know, this returns false if `self` is an instance of a subclass of the argument. – Steven Aug 06 '10 at 14:46
20

kind_of? and is_a? are synonymous. They are Ruby's equivalent to Java's instanceof.

instance_of? is different in that it only returns true if the object is an instance of that exact class, not a subclass.

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
user3622081
  • 201
  • 2
  • 2
7

Have look at instance_of? and kind_of? methods. Here's the doc link http://ruby-doc.org/core/classes/Object.html#M000372

Anand Shah
  • 14,575
  • 16
  • 72
  • 110
6

I've had success with klass, which returns the class object. This seems to be Rails-specific.

Sample usage:

class Foo
end

Foo.new.klass
# => Foo

Foo.new.klass == Foo
# => true

Foo.new.klass == "Foo"
# => false

There is also a method that accomplishes this: Object.is_a?, which takes the class object as an argument and returns true if self is an instance of the class or an instance of a subclass.

Steven
  • 17,796
  • 13
  • 66
  • 118
  • I wish I could pick two correct answers. Array doesn't have klass as a method, but it does have instance_of but active_record abjects do have .klass, i think. – NullVoxPopuli Aug 06 '10 at 16:49
  • `Array.class` should work just as well. I got mixed up in my answer because the library I'm using extends class `Object` with method `class`. – Steven Aug 06 '10 at 17:03
  • `my_instance.klass` does NOT work, at least not in 2020, with or without Rails. `my_instance.class` is the correct way to get an object's class. – David Hempy Sep 16 '20 at 17:06
0

Adding another answer for completeness. Sometimes, particularly during testing, we may not want to access another class by type, so given a Hash:

h = { one: 'Val 1' }

instead of writing:

h.is_a? Hash # true

we can write:

h.class.name == 'Hash' # true
Vlad
  • 3,866
  • 1
  • 24
  • 20