Topic: What's a good way to read =(x)?

Hey guys; beginner here.  I'm trying to find a way to understand =(x) when it's applied to a class method.  (in case you have it - Simply Rails 2 pg. 69).

In it, he refactors:

def set_mileage(x)
  @mileage = x
end

def get_mileage
  @mileage
end

to...

def mileage=(x)
  @mileage = x
end

def mileage
  @mileage
end

...and I'm just trying to understand how I should "read" this code to myself to make sense.  How do you read "def mileage=(x)" to yourself when looking over code?

"The definition of the method mileage, if an argument is passed (that's how I'm reading =(x) at the moment), is to set the @mileage instance variable to the argument."

Would that be accurate?

Edit: Ok, so just confused myself even more.  He doesn't pass the argument like normal, it's passed like this:

kitt.mileage = 5950

And this won't work:

kitt.mileage(5950)

Is this just a syntax thing; something I need to remember when using =(x) or is there some form of explanation behind it?

Last edited by caleb2001r (2009-10-29 12:09:35)

Re: What's a good way to read =(x)?

Ruby attributes (instance data) are not accessible from outside the class. This is a bit of syntactic sugar to provide getter and setter methods that you can use as if they were attributes. You can get the same effect by coding attr_accessor :mileage, and Ruby will generate the methods you see in the refactoring.

I *think* that kitt.mileage=(5950) ought to work, though, showing that mileage= is actually the name of the method...