On Sat, Sep 26, 2009 at 8:38 PM, Mario Gr
<[email protected]> wrote:
> Got it - maybe.  I found a good resource[1], but I am not sure I
> understand the value of the setter method in the first place. It would
> seem that benefit is being able to skip explicitly calling save on an
> object. Is that right?

The benefit of getter and setter methods are many - essentially they
allow you to perform operations on the variable before and after they
are retrieved or set. This is part of object-oriented methodology. But
in reference to your first question - "I was wondering what methods
ending in an equal sign meant", it is a feature of Ruby itself that
methods can end in "!", "?" and "=", and the community has taken these
to mean "potentially dangerous/exception creating", "interrogative
(should return a boolean)" and "sets a variable", respectively.

> If I had this method defined on my class:
>
>  def my_attribute=(some_value)
>   �...@some_value = some_value
>  end
>
> I could call:
>
> �[email protected]_attribute = new_value
>
> instead of:
>
> �[email protected]_attribute = new_value
> �[email protected]
>
> Is that the reason to define a setter method?

No, because in #my_attribute=, you did not call save. Here is a reason
to define a setter method:

class Shape
  def save_intersection=(shape)
    @intersection = self.calculate_intersection(shape)
  end
end

That is, we need to calculate the intersection of these two shapes and
then we can store the result in an instance variable. This is a good
use of the setter syntax, because it sets a variable, and we need to
do something "special". However, if we're not doing anything special
with the variable being set, it is preferable to write:

class Shape
  attr_accessor :points
end

Which automatically defines the methods #points, which gets the
instance variable @points, and #points=, which will set the instance
variable if you used it like:

shape = Shape.new
shape.points = [1.2, 3,3]


Colin

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to