Jul 072011

Just as you can check the class of an instance using .kind_of?, you can also see whether a specific class inherits from another class using the ‘<' operator.

As a simple example, you can see that ruby's String class inherits from Object.

irb(main):001:0> String < Object
=> true

So, let's create a class 'Foo' we can play around with.

irb(main):002:0> class Foo < String
irb(main):003:1> end
=> nil
irb(main):004:0> Foo
=> Foo

We can ask whether Foo inherits from String or Object:

irb(main):005:0> Foo < String
=> true
irb(main):006:0> Foo < Object
=> true
irb(main):007:0> String < Foo
=> false
irb(main):008:0> a = Foo.new('a')
=> "a"
irb(main):009:0> a
=> "a"
irb(main):010:0> a.class.name
=> "Foo"
irb(main):011:0> a.class < String
=> true
irb(main):012:0> a.kind_of? String
=> true

Kind of cool.