From: Yusuke ENDOH Date: 2008-05-31T19:10:48+09:00 Subject: [ruby-dev:34902] Suggestion: Integer#hex 遠藤です。 Integer#hex と #oct を追加するのはどうでしょうか。 String#hex たちの反転です。 10000.hex #=> "2710" irb を計算機代わりに使う場合に便利だと思います。 10000.to_s(16) はちょっと長すぎですし。 Index: numeric.c =================================================================== --- numeric.c (revision 16716) +++ numeric.c (working copy) @@ -3042,6 +3042,36 @@ /* * call-seq: + * int.hex => string + * + * Returns a string of hexadecimal digits; equivalent to int.to_s(16). + * + * 0.hex #=> "0" + * 10000.hex #=> "2710" + */ +static VALUE +int_hex(VALUE num) +{ + return rb_funcall(num, rb_intern("to_s"), 1, INT2FIX(16)); +} + +/* + * call-seq: + * int.oct => string + * + * Returns a string of octal digits; equivalent to int.to_s(8). + * + * 0.oct #=> "0" + * 10000.oct #=> "23420" + */ +static VALUE +int_oct(VALUE num) +{ + return rb_funcall(num, rb_intern("to_s"), 1, INT2FIX(8)); +} + +/* + * call-seq: * fix.zero? => true or false * * Returns true if fix is zero. @@ -3163,6 +3193,8 @@ rb_define_method(rb_cInteger, "ceil", int_to_i, 0); rb_define_method(rb_cInteger, "truncate", int_to_i, 0); rb_define_method(rb_cInteger, "round", int_round, -1); + rb_define_method(rb_cInteger, "hex", int_hex, 0); + rb_define_method(rb_cInteger, "oct", int_oct, 0); rb_cFixnum = rb_define_class("Fixnum", rb_cInteger); rb_include_module(rb_cFixnum, rb_mPrecision); Index: test/ruby/test_integer.rb =================================================================== --- test/ruby/test_integer.rb (revision 16716) +++ test/ruby/test_integer.rb (working copy) @@ -190,4 +190,14 @@ assert_equal(2 ** 50, Integer(2.0 ** 50)) assert_raise(TypeError) { Integer(nil) } end + + def test_hex + assert_equal("0", 0.hex) + assert_equal("2710", 10000.hex) + end + + def test_oct + assert_equal("0", 0.oct) + assert_equal("23420", 10000.oct) + end end -- Yusuke ENDOH