2012-09-24 38 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