Everything Is an Object (Ruby)

In Ruby, every value is an object — including numbers, strings, true, false, nil, and even classes themselves. Every operation is a method call on some object.

Ruby

Unlike languages that have 'primitives' separate from objects, Ruby has none. 5 is an instance of Integer, "hi" is a String, nil is the sole instance of NilClass, and even classes are objects (instances of Class). This means you can call methods on anything: 5.times, "hi".upcase, nil.to_s.

Operators are syntactic sugar for methods too — 2 + 3 actually sends the + message to the integer 2 with argument 3, which is why you can define + on your own classes. This uniformity is the heart of Ruby's design.

Because everything is an object responding to messages, Ruby leans on duck typing rather than rigid types, and its metaprogramming features let you inspect and modify objects (and classes) at runtime.

Examples

Ruby

puts 5.class
puts "hi".class
puts nil.class
puts 42.even?

Output:

Integer
String
NilClass
true

Learn it in a lesson

See also

Back to the Dictionary