1

私の目標は、各お茶に独自の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
4

1 に答える 1

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_」プレフィックスを削除することをお勧めします。それは不要で、少し読みやすくなります。

于 2012-09-24T23:45:46.403 に答える