Nicely formatting output to console, specifying number of tabs

前端 未结 7 1336
盖世英雄少女心
盖世英雄少女心 2020-12-24 02:01

I am generating a script that is outputting information to the console. The information is some kind of statistic with a value. So much like a hash.

So one value\'s

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-24 02:10

    String has a built-in ljust for exactly this:

    x = {"foo"=>37, "something long"=>42, "between"=>99}
    x.each { |k, v| puts "#{k.ljust(20)} #{v}" }
    # Outputs:
    #  foo                  37
    #  something long       42
    #  between              99
    

    Or, if you want tabs, you can do a little math (assuming tab display width of 8) and write a short display function:

    def tab_pad(label, tab_stop = 4)
      label_tabs = label.length / 8
      label.ljust(label.length + tab_stop - label_tabs, "\t")
    end
    
    x.each { |k, v| puts "#{tab_pad(k)}#{v}" }
    # Outputs: 
    #  foo                  37
    #  something long       42
    #  between              99
    

提交回复
热议问题