2013-12-16 128 views
-2

我在这里做错了什么?我试图获得销售税,并最终将其用于数学计算?Ruby类获得销售税

class Item 
    def initialize(type) 
     @type = type 
    def tax_calc(type) 
     if type.include?("book") 
      sales_tax = 0 
     else 
      sales_tax = 2 
     end 
    end 
end 


puts "what is type" 
type2 = gets 


Item.new(type2) 

puts sales_tax 
+3

你为什么不告诉我们它对你的行为如何,以及与你想要做什么相比这是怎么回事? –

回答

1

您当前的代码是缺少end和你有一个嵌套的方法定义,这是一个非常先进的话题,我没有看到它使用除了作为玩具之外,很多时候。

此代码将返回税号。

class Item 
    def initialize(type) 
    @type = type 
    end 
    def tax_calc 
    if @type.include("book") 
     @sales_tax = 0 
    else 
     @sales_tax = 2 
    end 
    end 
    def sales_tax 
    tax_calc 
    end 
end 

puts "what is type" 
type = gets 

purchase = Item.new(type) 
puts purchase.sales_tax 

我改变type2简单type因为没有理由担心镜像类由于范围内的局部变量。

这段代码远非最佳,但它至少是'工作代码'。

+0

这是不是一个税计算好设置?我会让它变得更好更复杂,这是一个糟糕的基础吗? – neil4real

+0

不过,正如锡文提到的那样,很难确切地告诉你想要做什么。在这一点上,你显然是返回税收分类,而不是计算。你会建立它,并有更多的问题,我确信。所以,我想你是在你的路上。我很积极,你的代码将会改变,而且这个代码可能不会像现在这样并且可能很快就会存在。你有一个好的开始,因为到目前为止,我们还没有看到漂浮物。 :) – vgoff

1

在你的代码,sales_taxinitialize方法的局部变量。它不在该范围之外。

下面就来获得销售税的一种方法:

class Item 
    def initialize(type) 
    @sales_tax = type.include?('book') ? 0 : 2 
    end 

    def sales_tax 
    @sales_tax 
    end 
end 

item = Item.new('foo') 
puts Item.new('foo').sales_tax