2012-09-24 30 views
1

我的目标是能够为每个茶分配自己的ID,比较茶之间的价格和权重,并在命令行中完成所有操作。什么是一个聪明的方法来做到这一点?这是我到目前为止的代码:在Ruby中创建多个对象,然后比较他们

class Tea 

    def initialize(name, price, shipping, weight) 
     @name = name 
     @price = price 
     @shipping = shipping 
     @weight = weight 
     get_tea_details 
     @total_price = total_price 
    end 

    def get_tea_details 
     puts "Enter name: " 
     @name = gets.chomp 
     puts "Enter price: " 
     @price = gets.chomp.to_f 
     puts "Enter shipping cost: " 
     @shipping = gets.chomp.to_f 
     puts "Enter weight: " 
     @weight = gets.chomp.to_i 
    end 

    def total_price 
     @total_price = @price + @shipping 
    end 

    def price_difference 
     price_difference = t1.total_price - t2.total_price 
     print "#{price_difference}" 
    end 

end 

puts "Do you want to compare teas?: " 
answer = gets.chomp 
if answer == "yes" 
t1 = Tea.new(@name, @price, @shipping, @weight) 
t1 = Tea.new(@name, @price, @shipping, @weight) 
end 

price_difference 
+0

我收到此错误: NameError:未定义的局部变量或方法'price_difference”主:对象 – user1695820

+0

你有很多问题在那里......这个错误是因为你想访问没有Tea对象的Tea类的一种方法。你必须做t1.price_difference。 您的价格差异功能也不起作用。注意我的例子。您需要将第二个Tea对象作为参数。您不希望在该方法中包含一个与方法名称相同的本地变量(price_difference)。 我会在我的例子中加入那个函数应该是什么样的。你应该真的阅读Ruby编程。运行一个教程。 –

+0

谢谢。我得到它与t1.price_difference(t2)一起工作。我会继续浏览教程。 – user1695820

回答

0

我不完全相信你问什么,但我的猜测是,你想知道如何编写一个函数来比较你的茶对象。你可以这样做:

class Tea 
    attr_accessor :name, :price 

    def price_difference(other) 
      print (@price - other.price).abs 
    end 

    def compare(other) 
     same = true 

     if(@name != other.name) 
      puts "They have different names." 
      same = false 
     end 

     if(@price != other.price) 
      puts "They have different prices." 
      same = false 
     end 

     if same 
      puts "They are exactly the same!" 
     end 
    end 
end 

t1 = Tea.new 
t2 = Tea.new 

t1.compare t2 
"They are exactly the same!" 

我还建议从变量中删除“tea_”前缀。这是没有必要的,并增加了一点可读性。

+0

谢谢!我如何计算t1和t2之间总价格的差异? – user1695820

+1

@ user1695820减去? –

+0

@DaveNewton哈哈,是的。 – user1695820