Tatva-Artha

meaning of "it"

Ruby gotcha: defining class in ruby

without comments

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.

http://www.tatvartha.com/wp-content/plugins/sociofluid/images/digg_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/reddit_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/stumbleupon_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/delicious_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/google_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/twitter_16.png

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Written by Sharad

July 23rd, 2009 at 8:19 pm

Posted in All

Leave a Reply