fixnum

Turning long fixed number to array Ruby

二次信任 提交于 2019-11-26 17:24:33
问题 Is there a method in ruby to turn fixnum like 74239 into an array like [7,4,2,3,9] ? 回答1: 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] 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

Ruby max integer

断了今生、忘了曾经 提交于 2019-11-26 10:24:25
问题 I need to be able to determine a systems maximum integer in Ruby. Anybody know how, or if it\'s possible? 回答1: Ruby automatically converts integers to a large integer class when they overflow, so there's (practically) no limit to how big they can be. If you are looking for the machine's size, i.e. 64- or 32-bit, I found this trick at ruby-forum.com: machine_bytes = ['foo'].pack('p').size machine_bits = machine_bytes * 8 machine_max_signed = 2**(machine_bits-1) - 1 machine_max_unsigned = 2*