Object-Oriented Programming in Ruby

Identifying Objects

In Ruby almost everything is an object - including numerics, booleans, strings and symbols - and each object in Ruby has a unique id.

1.object_id # => 3
"1".object_id # => 70102006679520
class Animal; end
Animal.object_id # => 70102006843460
Animal.new.object_id # => 70102007385240
Animal.new.object_id # => 70102024293860

Sending Messages

It could be argued that the basis of Ruby programming is sending messages to objects and dealing with their responses. 1+2 is really sending a message :+ to the object 1 with the argument of 2. The whole adding operation is really a syntactic sugar for 1.send(:+, 2)

Responding to Messages

Each object in Ruby responds to a message in one way or another. If the object knows how to handle the message it returns some value and if it does not it raises a NoMethodError.

class Animal
  def self.walk
    "Walking ..."
  end
end

Animal.walk # => "Walking ..."
Animal.fly # => NoMethodError: undefined method `fly' for Animal:Class

Self

As opposed to JavaScript where this might be undefined in Ruby there is always a self object. self means the current object within context of which methods are being defined and code evaluation is being effected. Even after directly accessing a Ruby console and without creating any objects there is a self.

$ irb
> self # => main

Methods defined within a context of main object are not anonymous functions as they are associated with the main object. This puts into question an existence in Ruby of pure procedural programming paradigm.

We use cookies and similar technologies to enhance the quality of services, maintain statistics and adjust marketing content. You will find more information in the Cookies Policy.

By clicking OK you grant consent to processing of your personal data by us and our Trusted Partners with the purpose of maintain statistics and adjustment of the marketing content pursuant to the Privacy Policy. If you wish to not grant that consent and/or limit its extent click Settings.