基数を保持した数値クラスとかどうだろう
発想元:http://d.hatena.ne.jp/tilfin/20081215/1229310421
Ruby M17Nのencodeを保持したStringみたいに、基数を保持したNumericがあれば面白いかなと思いついてやってみた。
class Integer attr_accessor :base def self.[] n, base = 10 n ensure n.instance_variable_set :@base, base end def to_sb base = @base to_s base end # これは動かない def to_s base = @base super base end end number = Integer[0xFF, 16] p number #=> 255 p number.base #=> 16 p number.to_s #=> "255" p number.to_sb #=> "ff"
force_encodingみたいなメソッドが必要なのか考えたけど不要っぽい。基数がなんであろうと数値自体は変わらないし。
Integer(Numeric)のインスタンスに特異メソッド「to_s」は定義できない*1。ちぃ、覚えた!
*1:普通はNumeric#to_sを再定義なんてしないので、最頻値最適化のためだと思う