% 字符串格式在类方法中不起作用? (红宝石)
知道如何使用 % 进行格式化来显示标题吗?我在类方法中什么也不做,但在实例方法中工作得很好
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有打印出在
self.display
中调用%
的结果,这就是您看不到标题的原因。尝试执行以下操作:您还可以使用
printf
,它进行格式化和打印:
You're not printing out the result of calling
%
inself.display
, which is why you're not seeing the headers. Try doing the following instead:You could also use
printf
, which does the formatting and printing: