小编Ser*_*aev的帖子

Ruby中的数组或散列

任何人都可以解释什么是更快的阅读,写在Ruby:一个Array或一个Hash?什么是ArrayHash?的用例?

Array.new
Hash.new
Run Code Online (Sandbox Code Playgroud)

ruby arrays hash

5
推荐指数
1
解决办法
152
查看次数

将整数转换为二进制字符串,用前导零填充

我想创建新方法Integer#to_bin,将十进制转换为二进制字符串.#to_bin的参数是位数.结果应该用前导零填充,以使其具有多个数字.

例:

1.to_bin(4)
#=> "0001"
1.to_bin(3)
#=> "001"
1.to_bin(2)
#=> "01"
7.to_bin(1)
#=> nil
7.to_bin
#=> "111"
et?.
Run Code Online (Sandbox Code Playgroud)

我尝试过的:

class Integer

    def to_bin(number=nil)
        if number == nil
          return self.to_s(2)
        else 
          s = self.to_s(2).size
          e = number-s
          one = '0'
          two = '00'
          three = '000'

        if e==one.size
          one+self.to_s(2)
        elsif e==two.size
          two+self.to_s(2)
        elsif e==three.size
          three+self.to_s(2)
        end
        end
    end
end
Run Code Online (Sandbox Code Playgroud)

如何将整数转换为用前导零填充的二进制字符串?

ruby ruby-on-rails

1
推荐指数
2
解决办法
5328
查看次数

标签 统计

ruby ×2

arrays ×1

hash ×1

ruby-on-rails ×1