Zach Smith
Zach Smith

Reputation: 8971

Pre-defining variables

This is my class structure:

class Commodity
  def initialize(name)
    @name = name
  end

  class PriceSeries
    def initialize(name)
      @name = name
    end
  end
end

I want to instantiate the Commodity class:

gold = Commodity.new("gold")

then instantiate the PricePoint class:

gold.xau = Commodity::PriceSeries.new("gold")

It seems that I can only do this with an attribute accessor called xau in the gold class. Is this the only way to define that variable?

def xau
  xau
end

I feel like this shouldn't be a function.

Upvotes: 0

Views: 40

Answers (3)

sawa
sawa

Reputation: 168269

It is not clear what you want to do, but it looks like you want to do this:

class Commodity
  def initialize(name)
    @name = name
    @xau = Commodity::PriceSeries.new(name)
  end
end

Then,

gold = Commodity.new("gold")

will automatically define

Commodity::PriceSeries.new("gold")

as the value of an instance variable @xau of gold.

Upvotes: 0

Jordan Running
Jordan Running

Reputation: 106147

Well, there are a lot of ways to do it, but attr_accessor is by far the simplest:

class Commodity
  attr_accessor :xau
end

gold = Commodity.new("gold")
gold.xau = some_value

What attr_accessor :xau does is defines a xau= method that assigns its argument to the instance variable @xau, and another method xau that returns the value of @xau. In other words, it basically does this:

class Commodity
  # Setter
  def xau=(value)
    @xau = value
  end

  # Getter
  def xau
    @xau
  end
end

For convenience and readability, Ruby lets you put whitespace before the = in gold.xau = foo, but in fact it's the same as the method call gold.xau=(foo).

Upvotes: 1

Linuxios
Linuxios

Reputation: 35788

I'm pretty sure what you want is attr_accessor:

class Commodity
  attr_accessor :xau
end

Which is essentially equivalent to this:

class Commodity
  def xau
    @xau
  end
  def xau=(value)
    @xau = value
  end
end

Upvotes: 0

Related Questions