简体   繁体   中英

% 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.display

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM