为什么不显示字符串?

时间:2015-05-20 12:20:23

标签: ruby-on-rails ruby

我创建了方法" to_s" :

  def to_s
    "#{self.name}:#{self.price}:#{self.weight}"
  end

当我通过" cart.add_item"

将产品添加到购物车时
@items = []
@items << AntiqueItem.new({:price => 111, :weight => 100, :name => 'car'})
@items << RealItem.new({:price => 111, :weight => 100, :name => 'kettle'})
@items << RealItem.new({:price => 200, :weight => 100, :name => 'dishwasher'})

cart = Cart.new('vitalik')

cart.add_item RealItem.new({:price => 111, :weight => 100, :name => 'car'})
cart.add_item RealItem.new({:price => 121, :weight => 100, :name => 'car'})
cart.add_item RealItem.new({:price => 151, :weight => 100, :name => 'kettle'})

p cart

在控制台信息中未显示字符串

E:\work\storeapp3\app\storeapp\shop>ruby init.rb
#<Cart:0x2685888 @items=[#<RealItem:0x2685828 @weight=100, @real_price=111, @name="car">, #<RealItem:0x2685738 @weight=100, @real_price=121, @name="car">, #<RealItem:0x2685648 @wei
ght=100, @real_price=151, @name="kettle">], @owner="vitalik">

也许我在某个地方犯了错误?

1 个答案:

答案 0 :(得分:5)

因为p显示在对象上调用inspect方法的结果。您可以改用puts