Turning long fixed number to array Ruby

前端 未结 7 761
我寻月下人不归
我寻月下人不归 2020-12-03 22:43

Is there a method in ruby to turn fixnum like 74239 into an array like [7,4,2,3,9]?

7条回答
  •  一生所求
    2020-12-03 23:01

    The divmod method can be used to extract the digits one at a time

    def digits n
      n= n.abs
      [].tap do |result|
        while n > 0 
          n,digit = n.divmod 10
          result.unshift digit
        end
      end
    end
    

    A quick benchmark showed this to be faster than using log to find the number of digits ahead of time, which was itself faster than string based methods.

    bmbm(5) do |x|
      x.report('string') {10000.times {digits_s(rand(1000000000))}}
      x.report('divmod') {10000.times {digits_divmod(rand(1000000000))}}
      x.report('log') {10000.times {digits(rand(1000000000))}}
    end
    
    #=>
                 user     system      total        real
    string   0.120000   0.000000   0.120000 (  0.126119)
    divmod   0.030000   0.000000   0.030000 (  0.023148)
    log      0.040000   0.000000   0.040000 (  0.045285)
    

提交回复
热议问题