Overriding attr_ * methods in Ruby
I am reading this book " Well Grounded Ruby " and this random question came to me. I know in Ruby that it is possible to reopen a class and overwrite a method.
Example:
class A
def x
"First definition of x"
end
def x
"Second definition of x"
end
end
test = A.new
test.x #returns "Second definition of x"
Based on the above results, I was curious if it is possible to overwrite a class method with attr_accessor
my own (random) definition. That's what I think:
class Dummy
attr_accessor :test
def self.attr_accessor(method_name)
puts "Overwrite the default functionality of attr_accessor by printing this text instead."
end
end
d = Dummy.new
d.test #not sure why this returns nil instead of putting my message
Dummy.attr_accessor(test) #fails because of ArgumentError: wrong number of arguments (0 for 2..3)
For the two examples above, I hope to understand Ruby better by working hard and asking questions to get your understanding.
source to share
Yes, it is possible and you just did it!
d.test #not sure why this returns nil instead of putting my message
nil
, attr_accessor :test
, , , Ruby attr_accessor
Dummy
. nil
, ... nil
.
Dummy.attr_accessor(test) #fails because of ArgumentError: wrong number of arguments (0 for 2..3)
, . :
Dummy.attr_accessor("method_name")
, test
. . Kernel.test()
http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-test.
, , , , - attr_accessor
.
, . , .
class Dummy
def self.attr_accessor(method)
puts 'your message here'
end
attr_accessor :test # message printed
end
d = Dummy.new
d.test # raises an error, since we aren't creating a test method anymore
Dummy.attr_accessor(test) #will still fail, read on
test
- Ruby, test
. - , . , ,
Dummy.attr_accessor(:test1)
, attr_accessor
, , self
. (IOW, attr_accessor
Module
, self
Module
)