Tuesday, October 11, 2011

Objects in Ruby


In Ruby, all numbers, strings, arrays, regular expressions, and many other entities are actually objects. Work is done by executing the methods belonging to the object:
3.succ                 # 4
"abc".upcase # "ABC"
[2,1,5,3,4].sort # [1,2,3,4,5]
someObject.someMethod # some result

In Ruby, every object is an instance of some class; the class contains the implementation of the methods:
"abc".class        # String
"abc".class.class # Class

In addition to encapsulating its own attributes and operations, an object in Ruby has an identity:
"abc".object_id   # 53744407

This object ID is usually of limited usefulness to the programmer.

No comments:

Post a Comment