tags:

views:

32

answers:

2

How do I assign a value to another class's initialize parameter in Ruby

class Ubac
  def initialize(p_str)
    @p_str=p_str
    (.....)
  end
  def method1
    (.....)
  end

end

class ReqQuote < Ubac
  def initialize(p_code)
     @code=p_code
     # here how do i initialize the @p_str to the value which is returned from the get_data method below.?
  end
  def get_data(symbol)
     (....) # fetch data
     data 
  end
  def methodx
    (.....)
  end


end

Here how do I initialize @p_str with the value which is returned from the get_data method as if p_str was initialized from the Ubac class's initialize?

A: 

You write @p_str = get_data(some_symbol).

Chuck
in ReqQuote class?
imaginea
+2  A: 

In this specific case you can just put @p_str= in Ubac#initialize. However, you can call Ubac's initialize from ReqQuote using super e.g.

class ReqQuote < Ubac
  def initialize(p_code)
     super(get_data(some_symbol))
     @code=p_code
  end
  ...

This is generally a good practice because it means any other initialisation code added to Ubac will also get executed when you create a ReqQuote.

mikej
thanks mikej :)
imaginea
Watch out calling get_data before the constructor is complete, this could lead to unexpected bugs. Especially if get_data calls other instance methods, or if get_data is overridden in a child class.
Douglas