From: Jeremy Bopp Date: 2010-10-06T04:31:42+09:00 Subject: Re: Calling a method with an instance On 10/5/2010 1:59 PM, Paul Roche wrote: > Hi. I'm playing around with creating methods and then creating an > instance that calls the instance. Here's my code..... > > > class Discount > attr_accessor :amount, :discount > > def initialize(am, dis) > @amount = am > @discount = dis > > end > > > def self.discount_amount(amt, disc) > newamount = amt - disc > end > > end > > > dis1 = Discount.new(100, 20) > > dis1.discount_amount(amount, discount) > > > The error I get is...... > > discount.rb:25:in `
': undefined local variable or method `amount' > for main > :Object (NameError) > > > What is the best way to call a method with an instance? > Thanks There are a couple issues. First of all, you are trying to use two variables (amount and discount) without giving them any values, in other words without defining them. That's why you get the error "undefined local variable or method `amount'". Perhaps you mean to use dis1.amount and dis1.discount instead. Once you clear that hurdle, you'll find you also declared the discount_amount method as a class method on Discount, not an instance method. However, you go on to call the method as an instance method of dis1. I think the corrected code would be as follows: Discount.discount_amount(dis1.amount, dis1.discount) -Jeremy