我知道如何使用%格式显示标题?我在类方法中什么都不做,但在实例方法中很好地工作
class Stats
attr_accessor :type, :count;
def initialize type
@type = type
@count = 0
end
def self.display
"%s %4s " % ["header1",'header2']
#puts 'headers'
ObjectSpace.each_object(Stats) { |o|
puts o
}
end
def to_s
"%-9s %4d " % [@type, @count]
end
end
videos = Stats.new 'Videos'
videos.count = 3
article = Stats.new 'Article'
webinars = Stats.new 'Webinars'
Stats.display
答案 0 :(得分:2)
您没有在%
中打印出调用self.display
的结果,这就是您没有看到标题的原因。请尝试执行以下操作:
def self.display
puts "%s %4s " % ["header1", "header2"]
ObjectSpace.each_object(Stats) {|o| puts o }
end
您还可以使用printf
进行格式化和打印:
def self.display
printf "%s %4s \n", "header1", "header2"
ObjectSpace.each_object(Stats) {|o| puts o }
end