0

Here is my class:

class Money
  def initialize(dollars, quarters, dimes, nickels, pennies)
    @coins = [ {:coin => dollars,  :price => 100},
               {:coin => quarters, :price => 25},
               {:coin => dimes,    :price => 10},
               {:coin => nickels,  :price => 5},
               {:coin => pennies,  :price => 1} ]
  end
  def count
    total = 0.00
    coins.each do |coin|
      next if coin[:price] == 0
      total += coin[:coin] * coin[:price]
    end
    total / 100
  end
end

and I am testing it like this:

money = Money.new( 5, 1, 2, 1, 0 )
puts "$%.2f" % money.count

I am receiving an error:

money.rb:12:in `count': undefined local variable or method `coins' for #<Money:0x2567310> (NameError)
    from money.rb:34:in `<main>'

which points to the line coins.each do |coin| and doesn't make sense to me because I thought that, if I prefix a variable with @, I could use it throughout my objects's methods (it will not carry over to a different object).

I got this working using different code that does:

@dollar = dollar
@quarter = quarter
...

for my initialize method (my count method was radically different), but now I am trying to create an array of hash tables so that I could refactor my count method.

Any help will be appreciated.

0

2 Answers 2

4

In your count() method refer to coins as @coins. Otherwise you've created a variable only available to the method your in and not referencing your instance variable that you created in your initialize()

So that it reads:

def count
    total = 0.00
    @coins.each do |coin|
        next if coin[:price] == 0
        total += coin[:coin] * coin[:price]
    end
    total / 100
end
Sign up to request clarification or add additional context in comments.

2 Comments

wow... i feel slightly dumbfound. I always though that you did not need to include the @ sign in the variable name, as I have used lines such as #{dollars} and it worked. Thanks for teaching me this simple mistake.
@randynewfield what you don't need to use when you do the string interpolation for an instance variable is the brackets. Such that you can do this "#@count"
2

If you create an instance variable (using @), you must always reference it with @.

def count
  total = 0.00
  @coins.each do |coin| #Here was your error
    next if coin[:price] == 0
    total += coin[:coin] * coin[:price]
  end
  total / 100
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.