ruby - understand self for attr_accessor class method -
class test class << self attr_accessor :some def set_some puts self.inspect = 'some_data' end def get_some puts self.inspect end end end test.set_some => test puts test.get_some.inspect => test nil
here above find self test not returning some_data
output.
but while modified in following way returns expected output
class test class << self attr_accessor :some def set_some puts self.inspect self.some = 'some_data' end def get_some puts self.inspect self.some end end end test.set_some => test puts test.get_some.inspect => test some_data
what differences?
edit
now in first example if set some
method as
test.some = 'new_data' puts test.some.inspect #=> new_data test.set_some puts test.get_some.inspect => new_data
now made me more confused.
some = :foo
makes ruby think should create new local variable name some
. if want call some=()
, have use explicit reciever - in self.some = :foo
. once lost bet on that... :-/
Comments
Post a Comment