为什么在Ruby中无法使用直到的用法,而在另一种用法却无法使用呢? [英] Why does this usage of until in Ruby not work, while another usage does?
问题描述
下面的代码给出了错误:
The code below gives an error:
def bubble_sort(arr)
until arr == arr.sort do
(arr.count - 1).times do |i|
(arr[i], arr[i + 1] = arr[i + 1], arr[i]) if (arr[i] > arr[i + 1])
end
end
arr
end
(eval):433:(eval):433:编译错误(SyntaxError)
(eval):433: (eval):433: compile error (SyntaxError)
(eval):426:语法错误,意外的kDO_COND,预期为kEND (arr.count-1).times做| i | ^
(eval):426: syntax error, unexpected kDO_COND, expecting kEND (arr.count - 1).times do |i| ^
(eval):433:语法错误,意外的kEND,期望$ end
(eval):433: syntax error, unexpected kEND, expecting $end
但是下面的另一个变体成功通过了.为什么?
But another variation of it below passes successfully. Why?
def bubble_sort(arr)
begin
(arr.count - 1).times do |i|
(arr[i], arr[i + 1] = arr[i + 1], arr[i]) if (arr[i] > arr[i + 1])
end
end until arr == arr.sort
arr
end
推荐答案
经过一些调试,这看上去像是1.8.7(labs.codecademy.com使用的版本)中irb
中的错误.在本地安装Ruby 1.8.7-p374时,我看到的是同一件事.但是,如果我将代码作为普通的Ruby文件运行,则可以正常工作.
After a bit of debugging, this looks like a bug in irb
on 1.8.7 (the version that labs.codecademy.com uses). Locally, when installing Ruby 1.8.7-p374 I see the same thing. However, if I run the code as a normal Ruby file, it works just fine.
However, Ruby 1.8.7 is officially retired, and it seems to me like the Codecademy Labs site is no longer maintained, either, so I recommend either learning Ruby with the "full" Codecademy site, or installing a more recent version of Ruby (I recommend 2.0.0) locally.
这篇关于为什么在Ruby中无法使用直到的用法,而在另一种用法却无法使用呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!