Nicely formatting output to console, specifying number of tabs

前端 未结 7 1334
盖世英雄少女心
盖世英雄少女心 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:32

    Provided you know the maximum length to be no more than 20 characters:

    printf "%-20s %s\n", value_name, value
    

    If you want to make it more dynamic, something like this should work nicely:

    longest_key = data_hash.keys.max_by(&:length)
    data_hash.each do |key, value|
      printf "%-#{longest_key.length}s %s\n", key, value
    end
    

提交回复
热议问题