2

I am trying to solve a recursion problem.

Code:

def divide(array)
  half = array.length/2
  return array if array.length == 1
  print ary1 = divide(array[0..half - 1])
  print ary2 = divide(array[half..-1])
  merge(ary1, ary2)
end
def merge(ary1, ary2)
  sorted = []
end

divide([10,9,8,-300,250,1,7,6,5,4,3,2])

If I don't comment out the sorted variable, it returns a few blank arrays mixed with numbers:

[10][9][8][][][-300][250][1][][][][7][6][5][][][4][3][2][][][]

I have no idea why naming a variable (but not calling it) would result in a different output than otherwise. Any insight into this would be appreciated.

1 Answer 1

4

Ruby functions which don't have an explicit return statement return the last evaluated expression. In your case that's sorted = [] which evaluates to just []. So merge will always return [].

A call to merge is the last expression in divide, so it too will return [] if it reaches that point.

For this reason, and for others, it's a good idea to always end functions with a return statement. Even if you intend to return the last evaluated expression, it makes your intent clear. If you intend to return nothing, just write return.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.