TheMayerof
TheMayerof

Reputation: 193

Why am I getting a nil value (Ruby)

I have 2 classes, When initializing the 'Shop' class I am giving the class a currency. How can I have "@checkout_currency" from my second class adopt the '@currency' value from the first class? @checkout_currency currently equals nil and I want it to equal "USD"

Here are my classes.

First..

require_relative 'convert'

class Shop

  DEFAULT_CURRENCY = "USD"

  def initialize(currency = DEFAULT_CURRENCY,
                 convert = Convert.new)
    @currency = currency
    @convert = convert

  end

  def self.currency
    @currency
  end

end

Second..

require_relative 'shop'

class Convert

  attr_reader :checkout_currency

  def initialize(checkout_currency = Shop.currency)
    @checkout_currency = checkout_currency
  end

end

Upvotes: 0

Views: 30

Answers (1)

simonwo
simonwo

Reputation: 3401

Yes, defining a method with self will make it a method on the class rather than a method on any instance of the class. But @currency is an instance variable – it’s different for every instance of Shop, and not defined for the Shop class itself. What if you had 3 Shop objects with different currencies?

The thing that is really wrong is your composition of objects – is Convert something that Shop constructs, or is it something that must be passed in fully formed? If you restructure to either of these, your problem goes away.

class Shop
  def initialize(convert, currency=DEFAULT_CURRENCY)
    @convert = convert
    @currency = currency
  end
end

convert = Convert.new(Shop.DEFAULT_CURRENCY)
shop = Shop.new(convert)

Or maybe:

class Shop
  def initialize(currency=DEFAULT_CURRENCY, convert_class=Convert)
    @convert = convert_class.new(currency)
    @currency = currency
  end
end

shop = Shop.new

Upvotes: 1

Related Questions