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
Hi I am building a method which sorts an array but accept a block. The block should take two arguments which represent the two elements currently being compared and sorting the element from the smallest to biggest.(https://www.theodinproject.com/courses/ruby-programming/lessons/advanced-building-blocks).
I am expecting the output to print ["hi", "hey", "hello"]
However it results in an error message:
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>'
Can someone explain where does the error come from, and how can I fix it? Also I realised that if I change the code array
(from second last line of the method block) to print array
; the code prints out ["hi", "hey", "hello"]
which is what I wanted and hence it should mean that my code is correct. Therefore my confusion of where did the error come from and how can i fix it?