我的目标是能够为每个茶分配自己的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
我收到此错误: NameError:未定义的局部变量或方法'price_difference”主:对象 – user1695820
你有很多问题在那里......这个错误是因为你想访问没有Tea对象的Tea类的一种方法。你必须做t1.price_difference。 您的价格差异功能也不起作用。注意我的例子。您需要将第二个Tea对象作为参数。您不希望在该方法中包含一个与方法名称相同的本地变量(price_difference)。 我会在我的例子中加入那个函数应该是什么样的。你应该真的阅读Ruby编程。运行一个教程。 –
谢谢。我得到它与t1.price_difference(t2)一起工作。我会继续浏览教程。 – user1695820