I was wondering why the integer class in Ruby lacked a method like octal, so i guess it would be nice to throw one in myself to make things easier.

class Integer

    def octal
        require ‘binary’
        num = self
        num_to_binary = num.binary
        array = %w(0 00)

        if num.size % 3 != 0
            array.each do |obj|
                concat_str = obj + num_to_binary
                if concat_str.size % 3 == 0
                    num_to_binary = concat_str
                end
            end
        end

        octal_mappings = {
             ‘000′ => ‘0′,
             ‘001′ => ‘1′,
             ‘010′ => ‘2′,
             ‘011′ => ‘3′,
             ‘100′ => ‘4′,
             ‘101′ => ‘5′,
             ‘110′ => ‘6′,
             ‘111′ => ‘7′
        }

        split_str = num_to_binary.scan(/…/)
        hex_array = []

        split_str.each do |str|

            hex_array.push octal_mappings[str]

        end

        hex_array.to_s
    end
end

Post a Comment

*
*