Attribute Fun with Ruby

I have been working with Ruby a lot lately. I came across something interesting today, so I thought that I would share it.Given the following code, what do you think will be printed to the screen?

class Person  attr_accessor :last_modified  def update_last_modified    last_modified = Date.today.to_s  endendperson = Person.newperson.update_last_modifiedp person.last_modified

Coming from C#, I thought that it would print today’s date. Once again, I was wrong. It prints nil. Why would it print nil?I assume Ruby thinks last_modified is a local variable and not an attr_accessor in the method update_last_modified. I guess this makes sense. How would Ruby know it was an accessor and not a variable?To get the results that I wanted the update_last_modified would have to change to the following.

def update_last_modified  self.last_modified = Date.today.to_send

It seems a little strange to see the self coming from C#. I would never put a this in front of a property setter.If you would like to see the full code snippet, you can check it out of subversion.https://esterline.devguard.com/svn/code/ruby_snippets

Advertisements

2 Responses

  1. […] – Improved Search Posted on October 1, 2007 by Adam Esterline As I noted in my last post, I have changed projects. In my current project, we are using a combination of Ruby and Java. A […]

  2. […] – Improved Search Posted on September 30, 2007 by Adam Esterline As I noted in my last post, I have changed projects. In my current project, we are using a combination of Ruby and Java. A […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: