def bubble_sort_by(array)
sorted = false
until sorted
swapped = false
(array.length - 1).times do |i|
if yield(array[i],array[i+1]) > 0
array[i], array[i+1] = array[i+1], array[i]
swapped = true
end
end
if swapped == false
sorted = true
end
end
array
end
print bubble_sort_by(["hi","hello","hey"]) do |left,right|
left.length - right.length
end
您好我正在构建一种方法排序数组,但接受一个块。该块应该有两个参数,它们代表当前正在比较的两个元素,并将元素从最小到最大排序(https://www.theodinproject.com/courses/ruby-programming/lessons/advanced-building-blocks)。无法打印从我的方法输出,本地跳转错误
我期待输出打印["hi", "hey", "hello"]
但是它导致的错误消息:
source_file.rb:8:in `block in bubble_sort_by': no block given (yield) (LocalJumpError)
from source_file.rb:7:in `times'
from source_file.rb:7:in `bubble_sort_by'
from source_file.rb:22:in `<main>'
有人能解释哪里从何而来的错误,我怎么能解决这个问题?我还意识到,如果我将代码array
(从方法块的最后一行开始)更改为print array
;代码打印出["hi", "hey", "hello"]
这是我想要的,因此它应该表示我的代码是正确的。因此,我对错误从何而来,以及如何解决这个错误感到困惑?
这可能是无关紧要的,但你怎么知道什么是块绑定?括号中还有任何文档吗? – roppo
@roppo对于多个链式方法调用,“do ... end”块语法将该块传递给最左边的方法。使用'{...}'语法将其传递给最右边的方法。有关详细信息,请参阅[权威性文档](https://docs.ruby-lang.org/en/2.4.0/syntax/calling_methods_rdoc.html#label-Block+Argument)。 –
@HolgerJust:虽然我不会称之为“链”。更像是......“嵌套”? –