[#1816] Ruby 1.5.3 under Tru64 (Alpha)? — Clemens Hintze <clemens.hintze@...>

Hi all,

17 messages 2000/03/14

[#1989] English Ruby/Gtk Tutorial? — schneik@...

18 messages 2000/03/17

[#2241] setter() for local variables — ts <decoux@...>

18 messages 2000/03/29

[ruby-talk:02321] Re: Question about attribute writers

From: Dave Thomas <Dave@...>
Date: 2000-03-31 23:49:24 UTC
List: ruby-talk #2321
Clemens Hintze <c.hintze@gmx.net> writes:

> Hmm difficult thingy here, I think. I would never assume that 
> 
>    age = 12;
> 
> could invoke a method, because I *know* that this syntax normally
> means assignment to a local variable. It would be very strange to me
> to use a method 'age=', if I can access @age directly. Invoking a
> method would furthermore be more costly.


The reason to make it use the method call is to decouple the use of
'age' from it's implementation. For example, say we had

  class Person
   def initialize(age)
     @age = age
   end
   def ageInMonths=(aim)
    @age = aim * 12
   end
  end

Then, sometime later we decided to change the *internal*
representation of age from 'years' to 'days'. Then we'd have

  class Person
   def initialize(age)
     @age = yearsToDays(age)
   end
   def ageInMonths=(aim)
    @age = aim * 12
   end
  end

But suddenly ageInMonths is wrong. If instead we'd used the method to
set it

  class Person
   def age=(newAge)
     @age = yearsToDays(newAge)
   end
   def ageInMonths=(aim)
    self.age = aim * 12
   end
  end

Then everything would have been fine.


However, you're right. We need to document that the interpretation of
'age' as a method call or variable is different depending on whether
there's an assignment.

Just as a matter of interest, though,

     class Fred
       private
       def age=(newAge)
         @age = newAge
       end
       public
       def setAge(newAge)
         age = newAge
       end
       def initialize
         @age=99
       end
     end

     f = Fred.new
     f.setAge(10)
     p f.inspect

Shouldn't Ruby throw an error when an assignment accessor is defined
to be private, as it can never be used.

> Perhaps it would be better to not change anything, and describe this
> case very carefully in the books and docs. Every language has its
> gotchas. We cannot eliminate all of them. This is one of Ruby.

d'accord


Dave

In This Thread