What is an object?
Everything in Ruby is an object. All objects have an identity; they can also hold state and manifest behaviour by responding to messages. These messages are normally dispatched through method calls.
A string is an example of a Ruby object. Each string object has its own identity exposed through methods like object_id, ==
and class
. It also has to store the value of the string and thus has state. Methods like split, upcase, downcase
exposes the behavior of the object.
But what about a method? Is that an object too? Ruby provides an object representation for methods as well. method(method_name)
returns a method object that holds method_name
. We cover this in detail in the RubyMonk Metaprogramming: Code Inspection chapter.
Blocks, lambdas, Class - all of the them are objects. Every expression in Ruby evaluates to an object. These are all objects:
Class
Module
Method
Object.new
"a string"
42
lambda { puts "This is a block of code. An object!"}
SomeUserDefinedClass.new