Ruby 计算Bignum中位数的方法

Ruby 计算Bignum中位数的方法,ruby,bignum,Ruby,Bignum,我正在编写一个ruby方法,如下所示: def build_array(word) word_copy = word array = [] length = word_copy.length for i in 1..length do array[i] = word_copy % 10 word_copy = word_copy/10; end puts array end 我想创建一个迭代器,它从1计数到Bignum中的位数 Bignum.length无

我正在编写一个ruby方法,如下所示:

def build_array(word)
  word_copy = word
  array = []
  length = word_copy.length
  for i in 1..length do
    array[i] = word_copy % 10
    word_copy = word_copy/10;
  end
 puts array
end
我想创建一个迭代器,它从1计数到
Bignum
中的位数

Bignum.length
无效。或者,有没有一种方法可以将一个
Bignum
分解成一个由其组成的数字组成的数组(这就是我试图实现的)


谢谢

您可以将其转换为字符串并计算其大小

b = 2_999_999_000_000_000
p b.class
#=> Bignum
p b.to_s.size
#=> 16
p b.to_s.split("").map(&:to_i)
#=> [2, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0]

您可以将其转换为字符串并计算其大小

b = 2_999_999_000_000_000
p b.class
#=> Bignum
p b.to_s.size
#=> 16
p b.to_s.split("").map(&:to_i)
#=> [2, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0]


你在找
num.to\u
?你在找
num.to\u
?而且速度更快!“虽然,如果可以的话,这不太明显。”塞尔吉奥图兰采夫我认为这是最直接的。我想不出比这更明显的答案了。也许只是我数学不好。而且速度也更快!“虽然,如果可以的话,这不太明显。”塞尔吉奥图兰采夫我认为这是最直接的。我想不出比这更明显的答案了。也许只是我数学不好。
b.to_.chars.map(&:to_I)
节省了一些笔划并减少了线条噪音。
b.to_.chars.map(&:to_I)
节省了一些笔划并减少了线条噪音。
Math.log10(x + 1).ceil # => 39