Ruby gotcha: defining class in ruby
Coming from Java this may be a little surprise that order of class initialization (order of method definitions) does impact the outcome of your program, as I just found out.
For example, consider 2 cases where I define a singleton class:
Case-1:
class A @@instance = A.new def self.instance @@instance end attr_reader :x private def initialize @x = 99 end end
Output:
>> A.instance.x => nil
Case-2:
class A private def initialize @x = 99 end @@instance = A.new public def self.instance @@instance end attr_reader :x end
Output:
>> A.instance.x => 99
The location of constructor/initialize() is different. And as we can see from output, the our constructor isn’t yet defined when A.new() was called in the first case and hence the @x instance variable didn’t get initialized the way we would have expected it to. The execution doesn’t complain since it uses the default/inbuilt constructor until our constructor gets defined.
Now I know.
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.





