I cant not understand why these code is well
class Class
def add_accessor(accessor_name)
self.class_eval %Q{
attr_accessor :#{accessor_name}
}
end
end
class Person
end
person = Person.new
Person.add_accessor :name
Person.add_accessor :gender
person.name = “Peter C.”
person.gender = “male”
puts “#{person.name} is #{person.gender}”
and these not work
class Person
def add_accessor(accessor_name)
self.class_eval %Q{
attr_accessor :#{accessor_name}
}
end
end
person = Person.new
Person.add_accessor :name
Person.add_accessor :gender
person.name = “Peter C.”
person.gender = “male”
puts “#{person.name} is #{person.gender}”
in the first group of code, the code is added to the class Class, so
any class has the method add_accesor, but i just want to the class
Person was the only class whom have it. Im just reading a book, and it
says that they put the code in the class Class just to all the class
has the method.
On Mon, Jan 24, 2011 at 12:58 PM, Lorenzo Brito M.
[email protected] wrote:
…, but i just want to the class Person was the only class whom have it.
then just put it Person
eg,
class Person
def self.add_accessor accessor_name
self.class_eval %Q{
attr_accessor :#{accessor_name}
}
end
end
#=> nil
person=Person.new
#=> #Person:0x871188c
Person.add_accessor :name
#=> nil
Person.add_accessor :gender
#=> nil
person.name=“Peter C.”
#=> “Peter C.”
person.gender=“male”
#=> “male”
person.name
#=> “Peter C.”
person.gender
#=> “male”
best regards -botp
Ok, thanks, in that way what actually we are doing is a class method
not? a static called in java or csharp
but the thing i really feel very weird is these
class Class
def add_accessor(accessor_name)
self.class_eval %Q{
attr_accessor :#{accessor_name}
}
end
end
class Person
end
person = Person.new
Person.add_accessor :name
but why the method added to Class works on Person as class method ? if
it is added in Class as instance method ?
On Mon, Jan 24, 2011 at 1:46 PM, Lorenzo Brito M.
[email protected] wrote:
Ok, thanks, in that way what actually we are doing is a class method
yes. a class method
not? a static called in java or csharp
similar
person = Person.new
Person.add_accessor :name
but why the method added to Class works on Person as class method ? if
it is added in Class as instance method ?
that means, Person is an instance of class Class
ie when you do,
class Person
end
ruby treats it as
Person=Class.new
best regards -botp
WOW thanks a lot, i really got crazy about that. i will continue to
reading the book but
as i see it, ruby really difers from other languate, his feautures are
powerfull if we can understand it.