Jacob Moore - 3 months ago 23

Ruby Question

I'm doing an assignment writing a recursive merge sort in ruby. I'm trying to break this down piece by piece in order to be able to wrap my head around it. What I have so far is trying to accomplish the "divide" step until there is only one element left in each array.

`a = [5,2,4,6,1,7,3,8]`

def divide(a)

return a if a.length < 2

else

arr1 = puts divide(a[0..a.length/2-1])

arr2 = puts divide(a[a.length/2..a.length])

end

Now after this first method is done I would think the output would be :

`[5] [8]`

But it prints out:

`5`

2

4

6

1

7

3

8

Wouldn't everything besides 5,8 be gone? At first arr1 is [5,2,4,6] then [5,2] then [5]. How do the rest of the numbers not disappear?

Answer Source

You have at least two problems.

First, the `else`

statement has no effect, it's not how you do `if else`

in Ruby.

Second, if `a.length < 2`

is `false`

then your method will return `nil`

. `puts`

returns `nil`

, `x = nil`

returns `nil`

.

I've added some prints to demonstrate how your code works, I hope it'll help:

```
$level = 0
def divide(arr)
return arr if arr.length < 2
$level += 1
puts "Working with array #{arr}"
arr1 = divide(arr[0..arr.length/2-1])
puts "Level = #{$level} arr1 = #{arr1}"
arr2 = divide(arr[arr.length/2..arr.length])
puts "Level = #{$level} arr2 = #{arr2}"
$level -= 1
nil
end
divide([5, 2, 4, 6, 1, 7, 3, 8])
```

The output:

```
Working with array [5, 2, 4, 6, 1, 7, 3, 8]
Working with array [5, 2, 4, 6]
Working with array [5, 2]
Level = 3 arr1 = [5]
Level = 3 arr2 = [2]
Level = 3 arr1 =
Working with array [4, 6]
Level = 4 arr1 = [4]
Level = 4 arr2 = [6]
Level = 4 arr2 =
Level = 4 arr1 =
Working with array [1, 7, 3, 8]
Working with array [1, 7]
Level = 6 arr1 = [1]
Level = 6 arr2 = [7]
Level = 6 arr1 =
Working with array [3, 8]
Level = 7 arr1 = [3]
Level = 7 arr2 = [8]
Level = 7 arr2 =
Level = 7 arr2 =
```