2010-02-22 4 views
0

어떻게 표시 할 수 있습니까? 헤더 %를 사용하여 서식을 지정합니까? 나는 수업 방법에서 아무것도하지 않습니다하지만, 인스턴스 메소드% 문자열 형식이 클래스 메소드에서 작동하지 않습니까? (루비)

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

당신은 헤더가 표시되지 않는 이유입니다, self.display에서 %를 호출 한 결과를 인쇄하지 않을에서 잘 작동합니다. 다음 대신 일을보십시오 :

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

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

또한 printf를 사용할 수있는 수행하는 서식 및 인쇄 :

+0

@Phil 로스 : 얼굴이 빨의 이모티콘은 무엇입니까? :-) 고맙습니다 – Radek

관련 문제