views:

53

answers:

1

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.display
+2  A: 

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
Phil Ross
@Phil Ross: what's the emoticon for blushing? :-) Thank you
Radek