Nicely formatting output to console, specifying number of tabs

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

    I wrote a thing

    • Automatically detects column widths
    • Spaces with spaces
    • Array of arrays [[],[],...] or array of hashes [{},{},...]
    • Does not detect columns too wide for console window

      lists = [ [ 123, "SDLKFJSLDKFJSLDKFJLSDKJF" ], [ 123456, "ffff" ], ]

    array_maxes

    def array_maxes(lists)
      lists.reduce([]) do |maxes, list|
        list.each_with_index do |value, index|
          maxes[index] = [(maxes[index] || 0), value.to_s.length].max
        end
        maxes
      end
    end
    
    array_maxes(lists)
    # => [6, 24]
    

    puts_arrays_columns

    def puts_arrays_columns(lists)
      maxes = array_maxes(hashes)
      lists.each do |list|
        list.each_with_index do |value, index|
          print " #{value.to_s.rjust(maxes[index])},"
        end
        puts
      end
    end
    
    puts_arrays_columns(lists)
    
    # Output:
    #     123, SDLKFJSLDKFJSLDKFJLSDKJF,
    #  123456,                     ffff,
    

    and another thing

    hashes = [
      { "id" => 123,    "name" => "SDLKFJSLDKFJSLDKFJLSDKJF" },
      { "id" => 123456, "name" => "ffff" },
    ]
    

    hash_maxes

    def hash_maxes(hashes)
      hashes.reduce({}) do |maxes, hash|
        hash.keys.each do |key|
          maxes[key] = [(maxes[key] || 0), key.to_s.length].max
          maxes[key] = [(maxes[key] || 0), hash[key].to_s.length].max
        end
        maxes
      end
    end
    
    hash_maxes(hashes)
    # => {"id"=>6, "name"=>24}
    

    puts_hashes_columns

    def puts_hashes_columns(hashes)
      maxes = hash_maxes(hashes)
    
      return if hashes.empty?
    
      # Headers
      hashes.first.each do |key, value|
        print " #{key.to_s.rjust(maxes[key])},"
      end
      puts
    
      hashes.each do |hash|
        hash.each do |key, value|
          print " #{value.to_s.rjust(maxes[key])},"
        end
        puts
      end
    
    end
    
    puts_hashes_columns(hashes)
    
    # Output:
    #      id,                     name,
    #     123, SDLKFJSLDKFJSLDKFJLSDKJF,
    #  123456,                     ffff,
    

    Edit: Fixes hash keys considered in the length.

    hashes = [
      { id: 123,    name: "DLKFJSDLKFJSLDKFJSDF", asdfasdf: :a  },
      { id: 123456, name: "ffff",                 asdfasdf: :ab },
    ]
    
    hash_maxes(hashes)
    # => {:id=>6, :name=>20, :asdfasdf=>8}
    

    Want to whitelist columns columns?

    hashes.map{ |h| h.slice(:id, :name) }
    # => [
    #  { id: 123,    name: "DLKFJSDLKFJSLDKFJSDF" },
    #  { id: 123456, name: "ffff"                 },
    #]
    

提交回复
热议问题