%字符串格式在类方法中不起作用? (红宝石)

时间:2010-02-22 10:59:29

标签: ruby methods string-formatting

我知道如何使用%格式显示标题?我在类方法中什么都不做,但在实例方法中很好地工作

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

1 个答案:

答案 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