Fixnum is considered an array in Ruby

I'm new to Ruby, and I'm trying to execute a merge sort algorithm , as mentioned on Wikipedia

I get a โ€œCompare Fixnum error with Array failed (ArgumentError)โ€ when comparing the first elements of a left and right array in a merge method. What could be the reason and how to solve this problem? Thanks:)

def mergeSort(array) if array.length == 1 return array end middle = array.length/2 - 1 left = array[0..middle] right = array[middle+1..array.length-1] left = mergeSort(left) right = mergeSort(right) merge(left,right) end def merge(left,right) result = [] while left.length > 0 || right.length > 0 if left.length > 0 && right.length > 0 one = left[0] two = right[0] puts ("one class is #{one.class} two class is #{two.class} two is #{two}") if one <= two result << left.shift else result << right.shift end elsif left.length > 0 result.push(left) left = [] else result.push(right) right = [] end end puts "result is #{result}" result end 
+4
source share
1 answer

The error in these lines:

  elsif left.length > 0 result.push(left) left = [] else result.push(right) right = [] end 

A simple example should indicate why:

 irb(main):067:0> a=[1,2] => [1, 2] irb(main):068:0> b=[3,4] => [3, 4] irb(main):069:0> a.push(b) => [1, 2, [3, 4]] 

Instead of push() try concat() .

+5
source

Source: https://habr.com/ru/post/1380983/


All Articles