控制台向后打印

时间:2015-07-27 01:37:18

标签: ruby

我试图让代码打印一个类的名称,然后在同一行上问候。例如:

(DriveThru): Hi, welcome to Starbucks! What can I get started for you?

这是我的代码:

module Order
  def order_drink
    "(#{self.class.name}): #{self.greeting}"
  end
end

class Lobby
  include Order
  attr_reader :name
  def initialize(name)
    @name = name
  end
  def greeting
    puts "Hi, welcome to Starbucks! How are you doing today #{self.name}?"
  end
end

class DriveThru
  include Order
  attr_reader :name
  def initialize(name)
    @name = name
  end
  def greeting
    puts "Hi, welcome to Starbucks! What can I get started for you #{self.name}?"
  end
end

dt = DriveThru.new("Tom")
lb = Lobby.new("Jessica")

puts dt.order_drink
puts lb.order_drink

当我运行代码时,它首先打印问候语,换行符,然后打印出类名:

"Hi, welcome to Starbucks! What can I get started for you?"
(DriveThru):

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您的greeting函数正在执行puts语句。由于Ruby(和大多数其他编程语言)的工作方式,order_drink方法将在返回自己的值之前首先评估greeting方法的内容(调用puts语句)。

在每个puts函数的开头删除greeting,例如:

class Lobby
  include Order
  attr_reader :name
  def initialize(name)
    @name = name
  end
  def greeting
    "Hi, welcome to Starbucks! How are you doing today #{self.name}?"
  end
end

这将导致您的脚本输出以下内容:

(DriveThru): Hi, welcome to Starbucks! What can I get started for you Tom?
(Lobby): Hi, welcome to Starbucks! How are you doing today Jessica?

也就是说,最好为greeting属性添加attr_reader,并在initialize方法(也称为构造函数)中设置其值,如下所示:

class Lobby
  include Order
  attr_reader :name, :greeting
  def initialize(name)
    @name = name
    @greeting = "Hi, welcome to Starbucks! How are you doing today #{name}?"
  end
end