Skip to main content

Ruby: Object Methods

As stated in the Datatypes section, the Ruby language implements all instances of data as an Object. One consequence of this is that these objects have a built-in set of methods which may be invoked with implied reference to the Object super class. Although beyond the scope of this primer, a review of Ruby's Class construct may satisfy any curiosity on how this mechanism is defined.

Typically, calling an Object's method involves first identifying the object either by object literal or identifier, following the identity with a period symbol (.), and following the symbol with the method identifier. Like programmer defined methods, a return value may be captured or utilized by the invoking script.

The following methods are available on all Objects.

Object.to_s

Object.to_s returns a string representation of an object. This is useful for comparing numbers and strings, and is often overridden in developer defined objects.

OBJECT.TO_S
puts 15.to_s
OUTPUT
15

Object.nil?

Object.nil? returns true or false depending on whether the object if of nil value or not. nil is a Ruby value representing a known nothing, and is common in binary tree algorithms.

OBJECT.NIL?
phone_number = is_dog ? nil : '555-555-9281'

if phone_number.nil?
puts 'Good dog!'
else
puts "Please call #{phone_number}."
end