如何确定Ruby中Fixnum的长度? [英] How do I determine the length of a Fixnum in Ruby?

查看:165
本文介绍了如何确定Ruby中Fixnum的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我写的脚本中,我想在Ruby中找到Fixnum的长度。我可以做< num> .to_s.length ,但有没有办法直接找到Fixnum的长度而不将其转换为字符串?

In the script I'm writing, I want find the length of a Fixnum in Ruby. I could do <num>.to_s.length, but is there any way to directly find the length of a Fixnum without converting it into a String?

推荐答案

puts Math.log10(1234).to_i + 1 # => 4

你可以像这样将它添加到Fixnum:

You could add it to Fixnum like this:

class Fixnum
  def num_digits
    Math.log10(self).to_i + 1
  end
end

puts 1234.num_digits # => 4

这篇关于如何确定Ruby中Fixnum的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆