Return arr the same as arr?


#1



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


Hello,

My code works, but I saw on the forum that people use "else return arr" instead of "else arr". Is there a difference or can you use either? Is one better than the other?

Thanks !


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


#2

Yes, when it is the last line of a block the return is implicit.

We cannot flat out say one is better. Each situation is different. Given the many different ways that we can do the same thing, it is probably best to not think qualitatively until you have a few miles of code under your belt. Then YOU get to decide which is better in the given circumstances. Limit the amount of subjective thinking and be as objective as possible.


#3

Thank you, that's helpful!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.