Ruby factory method returns a NoMethodError when it's called. What happened?

Refresh

February 2019

Views

6 time

0

I'm trying to integrate a factory method into this imperial-to-metric converter. I can make it work independently, but when it's iterated through a hash of ingredients it brings up a NoMethodError. What did I do wrong?

I've run independent instance variables through the factory without issue:

@item = "cups"
@number = 89.2
Gramulator.for(@number, @item) # => 828.0300000000001

I've confirmed that it works properly with inputs. I've even run it with @dough.unit and @dough.amount successfully:

Gramulator for(@dough.amount, @dough.unit) # => 828.0300000000001

But when I point it through the iteration method itself, @dough.gramulate doesn't work.

class Unit
  def initialize(amount)
    @amount = amount
  end

  def calculate
    @amount.to_f
  end
end

class Cup < Unit
  def calculate
    (super * 236.58)
  end
end

class Recipe
  attr_accessor :amount
  attr_reader   :name, :unit

  def initialize(ingredient_hash)
    @ingredient_hash = ingredient_hash
  end

  def gramulate
    puts "CONVERTED TO GRAMS:"
    @ingredient_hash.each do |name, quantity|
      quantity_array = quantity.split

      @name    =  name
      @amount  =  quantity_array[0].to_f
      @unit    =  quantity_array[1]

      Gramulator.for(@amount, @unit)
      puts "#{@name}: #{@amount} grams"
    end
  end
end

module Gramulator

  @units = {
    "cups"   => Cup
    # <other measurements>
  }

  def self.for(unit, amount)
    (@units[unit]).new(amount).calculate
  end
end

@dough = Recipe.new({
  bread_flour: 3.5 cups,
  # <other ingredients>
})

Expected result:

CONVERTED TO GRAMS:
bread_flour: 828.0300000000001 grams

Actual result:

CONVERTED TO GRAMS:
NoMethodError: undefined method 'new' for nil:NilClass

0 answers