Code & Clay – Notes to self. Mainly Ruby/Rails.

Use is_a? when checking class

Do not use == when checking that an object is of a given class.

Whilst it works here:

> Array.new.class == Array
=> true

…it won’t work with descendants of the class we’re checking against:

> class Thing < Array; end
=> nil
> Thing.new.class
=> Thing
> Thing.new.class == Array
=> false

Instead use is_a?:

> Array.new.is_a? Array
=> true
> Thing.new.is_a? Thing
=> true
> Thing.new.is_a? Array
=> true

If you really want to get to grips with Ruby development and gain a solid understanding of Object Oriented Design, I thoroughly recommend Sandi Metz's Practical Object Oriented Design in Ruby. It's the perfect introduction to OOP and pragmatic Ruby. You can buy it here.

“Meticulously pragmatic and exquisitely articulate, Practical Object Oriented Design in Ruby makes otherwise elusive knowledge available to an audience which desperately needs it. The prescriptions are appropriate both as rules for novices and as guidelines for experienced professionals.”

Katrina Owen, Creator, Exercism

Essential Reading: Learn Rails 6