2015-09-20 4 views
0

Я постоянно получаю следующее сообщение об ошибке при запуске этой программы:Проблемы, связанные с методом объема

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 через input3, чтобы увидеть новый экземпляр Receipt? (Я также играл с созданием его как синглтон, но не уверен, что я сделал это правильно ... Я переименовал переменные Receipt.var_name)

Заранее благодарен!

КОД:

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

Вы можете выполнить одно из следующих действий:

  • сделать input1, input2, input3 константы;
  • input1, input2, input3 методы;
  • input1, input2, input3 переменные класса;
  • input1, input2, input3 класс переменных экземпляра.

(то же самое относится и к non_tax, import_tax, sales_tax, round и т.д ..)

я бы ни с одним из первых двух вариантов.

Выбор второго варианта будет стоить вам меньше изменений кода.

+0

Спасибо! Я действительно вошел и внес переменные класса перед редактированием комментария ... мне не пришло в голову создавать методы для каждого из входов. На самом деле я надеялся сделать что-то более масштабируемым для большего количества ресурсов, но я не уверен, как это сделать (я начал с Ruby 3 дня назад!) Есть ли какие-нибудь советы? – capecoder

+0

вы можете прибегнуть к созданию некоторого файла конфигурации, имеющего все это, а затем просто доступ к нему в вашем классе. Но это будет новый вопрос, не стесняйтесь создавать новый –

Смежные вопросы