% 字符串格式在类方法中不起作用? (红宝石)

发布于 2024-08-22 01:55:02 字数 506 浏览 2 评论 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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苏佲洛 2024-08-29 01:55:02

您没有打印出在 self.display 中调用 % 的结果,这就是您看不到标题的原因。尝试执行以下操作:

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

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

您还可以使用 printf,它进行格式化和打印:

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

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文