Could this code be better?


#1



https://www.codecademy.com/courses/ruby-beginner-en-nOho7/0/4?curriculum_id=5059f8619189a5000201fbcb


I'm getting "Way to go" but I don't get anything printed out besides "nil". Should this work ???


def alphabetize(arr, rev = false)
arr = arr.sort!
puts arr


numbers = [5, 3, 2, 1]
num = alphabetize(numbers)
puts num
end


#2

def alphabetize(arr, rev=false)
    arr.sort!
end
numbers = [5, 2, 3, 1]
num = alphabetize(numbers)
print num

with reverse,

def alphabetize(arr, rev=false)    
    arr.sort!
    if rev
        arr.reverse!
    end
    arr
end

numbers = [5, 2, 3, 1]
num = alphabetize(numbers,true)
print num
puts
puts num
num.each { |x| puts x }

The gotcha isn't really aparent but it is there.

print numbers    # 5321

The numbers array is directly affected by the function. The fix for this is to not sort in place, nor assign it back on itself.

    temp = arr.sort
    # ...
    temp
end