ぷりてぃな配列

30分プログラム、その104。綺麗に配列を出力してみる。
sprintfを使えばいいじゃん、という言葉は聞こえないもん。

使い方

t = []
t << ['Alice',20]
t << ['Bob',10]
t << ['Charry',30]

puts t.map{|name,point|
  ["#{name}: ",'[','='*point,']']
}.to_s

というコードで

Alice:  [====================          ]
Bob:    [==========                    ]
Charry: [==============================]

が得られる。"["の位置がそろっているところがポイント。

ソースコード

to_sを書き換えるんじゃなくて、別のメソッドで実装したほうがいい気がしてる。まあ、いいや。

#! /opt/local/bin/ruby -w
# -*- mode:ruby; coding:utf-8 -*-
#
# prettyarray.rb - Pretty Format Array
#
# Copyright(C) 2007 by mzp
# Author: MIZUNO Hiroki <hiroki1124@gmail.com> 
# http://mzp.sakura.ne.jp/
#
# Timestamp: 2007/08/11 22:10:43
#
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Ruby itself.
#

class Array
  alias_method :_to_s_,:to_s

  def to_s
    if first.class == Array then
      widths = transpose.map{|item|
        item.map{|x| x.to_s.size }.max
      }
      map{|line|
        line.zip(widths).map{|cell,size|
          span = size - cell.to_s.size
          "#{cell}#{' ' * span}"
        }.join
      }.join("\n")
    else
      _to_s_
    end
  end
end

t = []
t << ['Alice',20]
t << ['Bob',10]
t << ['Charry',30]

puts t.map{|name,point|
  ["#{name}: ",'[','='*point,']']
}.to_s