ruby - 如何从整数中得到 10s、100s、1000s?

标签 ruby

ruby 中是否有允许将整数分解为 1、10、100、1000 等的方法?

我知道您可以将整数转换为字符串并解析该字符串以获得上述值,但我想像大多数其他事情一样,有一种非常简单的方法可以使用 ruby​​ 执行此操作。到目前为止我有这个:

1234.to_s.chars.reverse.each_with_index
.map{|character, index| character.to_i * 10**index }
# => [4, 30, 200, 1000]

但是在 ruby​​ 中有什么特定的东西可以做到这一点吗?

最佳答案

你可以这样做:

n = 1020304

Math.log10(n).ceil.times.with_object([]) do |i,a|
  n, d = n.divmod(10)
  a << d * 10**i
end
  #=> [4, 0, 300, 0, 20000, 0, 1000000] 

嗯。这看起来有点奇怪。也许返回一个散列会更好:

Math.log10(n).ceil.times.with_object({}) do |i,h|
  n, d = n.divmod(10)
  h[10**i] = d
end
  #=> {1=>4, 10=>0, 100=>3, 1000=>0, 10000=>2, 100000=>0, 1000000=>1} 

关于ruby - 如何从整数中得到 10s、100s、1000s?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31230815/

相关文章:

Ruby - Thor 首先执行特定任务

Ruby:如何要求和实例化目录中的所有文件?

Ruby 私有(private)类方法

ruby-on-rails - Rubygems 的 SSL 错误(无法连接)

ruby - 在使用 Ruby 连接到 HTTPS url 并将源数据传递给 Nokogiri 方面需要帮助

c++ - 尝试将两个视频与 pHash 库及其 ruby​​ 绑定(bind)进行比较时出现段错误

ruby - 是否可以在 Ruby 模块或类中分配 "default method"?

ruby-on-rails - 如何从 Amazon ItemSearch/ItemLookup 获取销售排名

ruby-on-rails - 使用 Elasticsearch 与 Searchkick on Rails 通过关联查找用户项目?

ruby - 正则表达式匹配多个字符串 - Ruby