On lesson 5


#1

def alphabetize(arr, rev = false)
    arr.sort!
    if rev
        arr.reverse!
    end
end
numbers = [6, 9, 1, 2, 5, 4, 8, 7, 3]
puts alphabetize(numbers, true)

if I type this I get an error message but if I add the else

def alphabetize(arr, rev = false)
    arr.sort!
    if rev
        arr.reverse!
    else
        arr.sort!
    end
end
numbers = [6, 9, 1, 2, 5, 4, 8, 7, 3]
puts alphabetize(numbers, true)

it works why if I've already sorted it right before the if do I need to sort it again for the code to work?


#2

In a Ruby block, the last line that's executed in the block is what gets returned. In an if statement, I think there's an implied "else nil" that gets tacked on at the end. So, when you don't have the else at the end, you're returning nil instead of arr.

You don't have to sort again in the else part of the conditional though. You can just return arr.

if rev
      arr.reverse!
else
    arr
end