Strange Symphonies Don’t worry, be happy

3Jun/070

Everything Is An Object in Ruby

In Ruby, everything is an object.

That's right, including those "primitive types" as understood by other languages.

1.class # Fixnum
1.0.class # Float
true.class # TrueClass
false.class # FalseClass
nil.class # NilClass
true.class.class # Class
Array.class # Class
String.class # Class

Even classes are an instance of a class. Funky.

But what does mean?

For starters, it means everything has an interface for method invocation.

5.times do
  puts "Hello World"
end

Results:


Hello World
Hello World
Hello World
Hello World
Hello World

3.141_592_653_589_79.ciel # 4
2.718_281_828_459_05.floor # 2

Note: In Ruby you can make numbers easier to read by separating them with a delimiter (in this case the underscore).

To find out whether an object can "respond to" a certain method invocation, is as simple as:

1.respond_to? :downcase # false
"Will this string respond?".respond_to? :downcase # true

As a Numeric (1) cannot respond to a downcase, it returns a false.

Note:

  • :downcase is a Symbol. Anything prefixed with a colon is a Symbol. A Symbol is like a quick way to represent a constant without defining it, or giving it any value. For all intensive purposes its to make it easy to identify certain things in Ruby. For example, fields, methods, keys, and many more, it is not limited to just this.
  • The String method downcase helps to downcase/lowercase the letters

Epiphany


When I started Ruby programming, I was at awe when I saw object instantiation.

In Ruby:

user = User.new

Compare to the traditional style, in PHP:

$user = new User();

new is a class method of the User class, and not a statement of its own.

Behind The Scenes: The Creation of a Ruby Class

So since all classes are a class of Class, when you define a new class, like so:

class User
end

Behind the scenes you are actually creating an instantiation from the Class class:

User = Class.new

They both accomplish the same thing.

Together With The Power of Open Classes

As everything is an object, and Ruby allows Open Classes, the core classes of Ruby can be easily extended to adapt to your needs. See my previous posts about Open Classes.

Example:

51.weeks # 30844800
365.days # 31536000
15.minutes + 3.days + 4.hours # 274500

Related posts

Tags

Tagged as: Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.