LoginSignup
3
3

More than 5 years have passed since last update.

Ruby | 10進数 ( decimal ) から20進数 ( vigesimal ) を取得する

Posted at

Ruby | 10進数 ( decimal ) から20進数 ( vigesimal ) を取得する

概要

10進数から20進数を取得します。
20進数を取得するには、 Integer#to_sメソッドの引数に基数20を渡します。

19.to_s(20) # => j
20.to_s(20) # => 10

サンプルコード

1から40までの数値配列について、
2/8/10/16/20 進数の表を作成します。

require 'tbpgr_utils'

results = [['decimal', 'binary', 'oct', 'hex', 'vigesimal']]
[*1..40].each do |decimal|
  memo = [decimal]
  [2, 8, 16, 20].each do |cardinal_number|
    memo << decimal.to_s(cardinal_number)
  end
  results << memo
end

print results.to_table

__END__
Array#to_tableは 自作gem tbpgr_utils のメソッドです。
Array[Array, Array, Array...] をパイプ区切りのテーブルフォーマットにして出力します。

出力

|decimal|binary|oct|hex|vigesimal|
|      1|     1|  1|  1|        1|
|      2|    10|  2|  2|        2|
|      3|    11|  3|  3|        3|
|      4|   100|  4|  4|        4|
|      5|   101|  5|  5|        5|
|      6|   110|  6|  6|        6|
|      7|   111|  7|  7|        7|
|      8|  1000| 10|  8|        8|
|      9|  1001| 11|  9|        9|
|     10|  1010| 12|  a|        a|
|     11|  1011| 13|  b|        b|
|     12|  1100| 14|  c|        c|
|     13|  1101| 15|  d|        d|
|     14|  1110| 16|  e|        e|
|     15|  1111| 17|  f|        f|
|     16| 10000| 20| 10|        g|
|     17| 10001| 21| 11|        h|
|     18| 10010| 22| 12|        i|
|     19| 10011| 23| 13|        j|
|     20| 10100| 24| 14|       10|
|     21| 10101| 25| 15|       11|
|     22| 10110| 26| 16|       12|
|     23| 10111| 27| 17|       13|
|     24| 11000| 30| 18|       14|
|     25| 11001| 31| 19|       15|
|     26| 11010| 32| 1a|       16|
|     27| 11011| 33| 1b|       17|
|     28| 11100| 34| 1c|       18|
|     29| 11101| 35| 1d|       19|
|     30| 11110| 36| 1e|       1a|
|     31| 11111| 37| 1f|       1b|
|     32|100000| 40| 20|       1c|
|     33|100001| 41| 21|       1d|
|     34|100010| 42| 22|       1e|
|     35|100011| 43| 23|       1f|
|     36|100100| 44| 24|       1g|
|     37|100101| 45| 25|       1h|
|     38|100110| 46| 26|       1i|
|     39|100111| 47| 27|       1j|
|     40|101000| 50| 28|       20|
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3