Error:

Check if class exists

def class_exists?(class_name)
  klass = Module.const_get(class_name)
  return klass.is_a?(Class)
rescue NameError
  return false
end

Define class

class MyClass
  def initialize()
    # do something
  end
end

class AnotherClass < MyClass
  def initialize()
    super
    # do something
  end
end

Call parent's constructor

class MyClass
  def initialize(name)
    @name = name
  end
end

class AnotherClass < MyClass
  def initialize()
    super "fixed name"
    # do something
  end
end

Define class variable

class MyClass
  @@pieces = 3
end

Define instance variable

class MyClass
  @pieces = 3
end

Define class method

class MyClass
  def self.action
    puts "Action!"
  end
end

MyClass.action

Define instance method

class MyClass
  def action
    puts "Action!"
  end
end

MyClass.new.action

Define class constant

class MyMath
  TAU = 2*Math::PI
end

MyMath::TAU

Add method to existing module

module Math
  def self.circumference(radius)
    return 2*Math::PI*radius
  end
end

Math.circumference(10) # => 62.83185307179586

Add method to existing class

class Array
  def has_odd_numbers?
    return self.index { |x| return (x % 2) == 1 } != nil
  end
end

[0, 2, 4].has_odd_numbers? # => false
[1, 2, 4].has_odd_numbers? # => true

Get class of the object

klass = 'str'.class # => String
[1, 2, 3].kind_of?(String) # => false
[1, 2, 3].kind_of?(Array)  # => true

Getters and setters for instance property

class MyClass
  attr_accessor :name
  attr_reader :age
  attr_writer :writeonly
end

obj = MyClass.new
obj.name = 'Pluto'
puts obj.name

Check if instance has method

s = "test"
s.respond_to?('length')     # => true
s.respond_to?(:length)      # => true
s.respond_to?("celebrate!") # => false

Check if method defined for class

String.method_defined?(:length)      # => true
String.method_defined?("celebrate!") # => false
String.respond_to?(:length)          # => false
String.respond_to?(:new)             # => true

List all methods for class

class MyClass
  def instance_method
  end
  def self.class_method
  end
end

MyClass.methods # => [:class_method, :allocate, ...
MyClass.instance_methods # => [:instance_method, :nil?, ...

List all variables for instance

class MyClass
  @instance_var = 1
  def initialize
    @another_instance_var = 3
  end
end

MyClass.instance_variables
MyClass.new.instance_variables

Check whether a class is a subclass of another

class MyClass
end

class AnotherClass < MyClass
end

MyClass < AnotherClass # => false
MyClass < MyClass      # => false
AnotherClass < MyClass # => true