Вопрос

I thought Ruby automatically converts to Bignum. I found confirmation here

However, it is not happening:

ruby 1.8.7 (358) [universal-darwin12.0]
>> 2 ** 62    
=> 4611686018427387904
>> 2 ** 63
=> -9223372036854775808   #why minus - how about automatic Bignum conversion?
>> 2 ** 64
=> 0                      #- how about automatic Bignum conversion?                       
Это было полезно?

Решение

Use a Newer Ruby Version

Ruby 1.8.7 is (in Internet terms) ancient. Use something more recent. For example:

[1] pry(main)> RUBY_VERSION
=> "2.0.0"
[2] pry(main)> 2 ** 63
=> 9223372036854775808
[3] pry(main)> 2 ** 64
=> 18446744073709551616

Другие советы

That is probably a bug in the old version of Ruby. Switch to a newer version, the problem is gone. Today is the release day for Ruby 2.0. Ruby 1.8 will be dead soon. On my Ruby 1.9.3, I just did 2**1000000 without any problem except that it goes on for a while, so I had to terminate it.

Most likely a bug specific to the build you're using. For example, when I do ruby -v I get:

ruby 1.8.7 (2011-02-18 patchlevel 334) [i686-darwin12.2.1], MBARI 0x6770, Ruby Enterprise Edition 2011.03

...and in an irb session I get:

1.8.7 :006 > 2 ** 64
 => 18446744073709551616 
1.8.7 :007 > (2 ** 64).class
 => Bignum 
1.8.7 :008 > RUBY_VERSION
 => "1.8.7" 

I also don't get this problem if I use newer versions. If you can post your output from ruby -v that would shine some light on the situation. For example Ruby REE vs. MRI vs. JRuby, etc.

Also, and this is just an opinion so take it for what it's worth, but I don't think Apple is very good about keeping their built-in version of Ruby updated, so just in case you're using the built-in version then consider moving to another build.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top