问题
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: compile error (SyntaxError)
(eval):426: syntax error, unexpected kDO_COND, expecting kEND (arr.count - 1).times do |i| ^
(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:
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.
回答2:
I don't know why, but if you change the first code to the following it'll work out:
def bubble_sort(arr)
total = (arr.count - 1)
until arr == arr.sort do
total.times do |i|
(arr[i], arr[i + 1] = arr[i + 1], arr[i]) if (arr[i] > arr[i + 1])
end
end
arr
end
I've tested it with your link, so I'm guessing maybe it isn't properly configured, cause when I first added that total
in until
, it turned into an infinite loop. But someone has to check it against ruby, it maybe a bug.
回答3:
In Ruby, the until
block doesn't use do
, so you should do something like this:
def bubble_sort(arr)
until arr == arr.sort
(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
Edit: Expanded the code so it includes the algorithm from the original question. This code works for me on ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.4.0]
.
来源:https://stackoverflow.com/questions/17754479/why-does-this-usage-of-until-in-ruby-not-work-while-another-usage-does