谈到长期固定数量的数组红宝石 [英] Turning long fixed number to array Ruby

查看:127
本文介绍了谈到长期固定数量的数组红宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有红宝石的方法把像长整数到74239像一个数组[7,4,2,3,9]

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

推荐答案

您不需要采取通过串地往返于这样的事情:

You don't need to take a round trip through string-land for this sort of thing:

def digits(n)
    Math.log10(n).floor.downto(0).map { |i| (n / 10**i) % 10 }
end

ary = digits(74239)
# [7, 4, 2, 3, 9]

这不以为 N 是积极的,当然,在滑倒 N = n.abs 进入混合罐如果需要照顾的。如果您需要包括非正值,则:

This does assume that n is positive of course, slipping an n = n.abs into the mix can take care of that if needed. If you need to cover non-positive values, then:

def digits(n)
    return [0] if(n == 0)
    if(n < 0)
       neg = true
       n   = n.abs
    end
    a = Math.log10(n).floor.downto(0).map { |i| (n / 10**i) % 10 }
    a[0] *= -1 if(neg)
    a
end

这篇关于谈到长期固定数量的数组红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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