我的目标是能够为每个茶叶分配自己的ID,比较茶叶之间的价格和重量,并在命令行中完成所有操作。这是一个聪明的方法吗?到目前为止,这是我的代码:
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 :(得分:0)
我不确定你在问什么,但我想你想知道如何编写一个函数来比较你的Tea对象。你可以这样做:
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_”前缀。这是不必要的,并增加了一点可读性。