开发者

% string formatting doesn't work in class methods? (ruby)

any idea how I can display headers using % for formatting? I does nothing in class method but works nicely in instance method

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.d开发者_Python百科isplay


You're not printing out the result of calling % in self.display, which is why you're not seeing the headers. Try doing the following instead:

def self.display
  puts "%s %4s  " % ["header1", "header2"]

  ObjectSpace.each_object(Stats) {|o| puts o }
end

You could also use printf, which does the formatting and printing:

def self.display
  printf "%s %4s  \n", "header1", "header2"

  ObjectSpace.each_object(Stats) {|o| puts o }
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜