Everything is an object

Posted by admin, Sun Mar 04 23:29:00 UTC 2007

Ok - this one is for anyone new to rubyonrails and struggling to come to terms with variables - especially if they've come from a traditional (none OO) language.

In simple terms, there is only one variable type in ruby - a reference to an object. A pointer if you will.

So, there is no option to pass something to a sub-routine by value - the default in most languages - everything is passed by reference.

This usually raises the question of why, then, if passing - say - a string to a method, aren't the changes made to the string reflected outside the method ?

Take this code as an example -

1
2
3
4
5
6
7
8
def alter_a_string(s)
 s = s + ' cheese'
end

t = 'I eat'
alter_a_string(t)
puts t
=> 'I eat'

Why is this so if the variable was passed as a reference ?

It's actually pretty simple why - the s = s + 'cheese' doesn't modify the object pointed to by s - it creates a new object based on s and appends 'cheese' to it. + is a method on the String class that returns a new object.

Methods that affect the object itself in ruby usually have ! at the end of their names to show this - such as String.chomp!

The correct way to get our example above working as intended would be to use the << method. << in ruby has been adopted as the append method.

1
2
3
4
5
6
7
8
def alter_a_string!(s)
 s << ' cheese'
end

t = 'I eat'
alter_a_string!(t)
puts t
=> 'I eat cheese'

Filed Under: Rails | Tags:

Comments

Have your say

A name is required. You may use HTML in your comments.