简体   繁体   中英

Different 'upto' behavior in ruby on difference machines (`upto': no block given (LocalJumpError))

This code works on one machine but not the other:

puts 1.upto(5)

On the working machine, the code returns '#'.

On the other machine, I get this error:

test.rb:1:in `upto': no block given (LocalJumpError) from test.rb:1

Both machines have rails 2.2.2. The machine where this code works has ruby 1.8.7, while the two machines where this code doesn't work have ruby 1.8.6 and ruby 1.8.7 enterprise edition respectively.

Yes turns out in ruby 1.8.6 upto requires a block, while 1.8.7 a block is not necessary.

So solution is either to upgrade to 1.8.7 or use a block or do 1...4.to_a.

To get the 1.8.7+ behaviour in 1.8.6 you can do:

require 'enumerator'
1.enum_for(:upto, 5)

Which works the same on all versions and is functionally equivalent to 1.upto(5) without block in 1.8.7+ (though a little more verbose).

Though in this specific case you can of course just use a range.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM