I’m reading this book “The Well-Grounded Rubyist” and this random question came to me. I know in Ruby that it’s possible to re-open a class and overwrite the 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 results above, I was curious if it was possible to overwrite the class method attr_accessor with my own (random) definition. Here’s what I’m thinking:
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’m hoping to understand Ruby better by tinkering around and asking questions to get your insight.
Yes, it is possible, and you just did it!
returns
nilbecause you usedattr_accessor :testbefore redefining it below, as such, Ruby performedattr_accessor‘s default behavior and created a member and accessors in theDummyclass. It returnsnilbecause the member’s value is unset…nil.fails not for the reason you think. This call works:
The problem is you are calling a method named
testand not providing all of it’s expected values. See the docs forKernel.test()http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-test.The error message you are seeing is because you are calling the test method incorrectly, NOT because of a mistake in your redefinition of
attr_accessor.