方法范围问题

时间:2015-09-20 12:23:53

标签: ruby variables scope

运行此程序时,我不断收到以下错误:

taxed_output.rb:30:in `initialize': undefined local variable or method `input1' for #<Receipt:0x007fd8f511b428> (NameError) from taxed_output.rb:81:in `new' from taxed_output.rb:81:in `<main>'

我知道这可能与变量范围有关,而且我是Ruby的新手。有什么方法可以调整我的代码以允许新input1实例看到input3Receipt吗? (我也玩过将它创建为单身,但我不确定我做得对......我重命名变量Receipt.var_name

提前致谢!

CODE:

class Receipt

input1 = [ "1 imported box of chocolates at 10.00", "1 imported bottle of perfume at 47.50" ]
input2 = [ "1 book at 12.49", "1 music CD at 14.99", "1 chocolate bar at 0.85" ]
input3 = [ "1 imported bottle of perfume at 27.99", "1 bottle of perfume at 18.99", "1 packet of headache pills at 9.75", "1 box of imported chocolates at 11.25" ]

non_tax = [ "chocolate", "chocolates", "book", "pills" ]

import_tax = 0.05
sales_tax = 0.10
round = 20.0

def div
    "-" * 10
end #div

def initialize
    puts div + "OUTPUT 1" + div
    get_input(input1)
    puts div + "OUTPUT 2" + div
    get_input(input2)
    puts div + "OUTPUT 3" + div
    get_input(input3)
end #initialize

# GET_INPUT: splits input arrays and saves values into individual variables
def get_input (input_arr)
    total_tax = 0
    total_price = 0
    input_arr.each do |item|
       #items
           split_item_array = item.split
           qty = split_item_array[0].to_i
           price = split_item_array[-1].to_f
           p = item.split(" at ")
           product_name = p[0].delete("/0-9/").strip
       #taxes
           tax = tax_cal(price, product_name)
           total_tax += tax
           taxed_price = (price.to_f + tax)
           total_price += taxed_price
        puts "#{qty} #{product_name}: #{tax_price.round(2)}"
    end #each
    puts "Sales Tax: #{total_tax}.round(2)"
    puts "Total: #{total_price}.round(2)"
end #def (get_input)

# TAX_CAL: assesses applicable taxes based on product characteristics
def tax_cal (price, product)
    tax_exclude = []
    a_product = product_name.split(" ")
    tax_exclude = a_product & non_tax
    import_sales_tax = import_tax + sales_tax

    if product.include?(‘imported’) and tax_exclude.count != 1
      tax = price.to_f * import_sales_tax
    elsif product.include?(‘imported’) and tax_exclude.count == 1
      tax = price.to_f * import_tax
    elsif tax_exclude.count != 1
      tax = price.to_f * sales_tax
    else
      tax = 0
    end #if

    return tax
end #def (tax_cal)

end #class

Receipt.new

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作之一:

  • 制作input1input2input3常数;
  • 制作input1input2input3方法;
  • 制作input1input2input3类变量;
  • 制作input1input2input3类实例变量。

(这同样适用于non_taximport_taxsales_taxround等。)

我会选择前两个选项中的任何一个。

选择第二个选项会减少代码更改费用。