What's wrong with my code! thanks


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

number=[1,3,2,1,3,4]

alphabetize(number)

puts number

this is my code ,it works ! but there is a error
It looks like your method doesn't default to alphabetizing an array when it doesn't receive a second parameter.


#2

Hint: You have to return the final arr from your alphabetize method.


#3

why i need return?:flushed:


#4

Because the exercise requires you to do so. I can understand your confusion, you want to ask:

Question: We didn't have the return statement in the previous exercise. Why do we have to insert the return statement in this exercise then?

Answer:

On the previous exercise, we had this code:

def alphabetize(arr)
    arr.sort!
end

Since, here, arr.sort! is the last statement of the method alphabetize, it also becomes the return value of that method. Hence, even though you don't have an explicit return statement, the method will still return a value.

Then, you modify the code to:

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

number = [1,3,2,1,3,4]

(Note that, here, arr.sort! is not the last statement of the code, it is arr.reverse! instead.)

So, when you do: alphabetize(number, true) the method executes till the last statement and returns a value. However, when you do alphabetize(number) only, the if condition if rev is false and so the last statement is not executed. And therefore, no value is returned.

But the code expects you to return a value, therefore, you need to add an explicit return statement at the end like this:

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

    return arr
end

to make your code complete and correct.

I hope it helps! :smile:


#5

thanks a lot ,i understand it:grinning:


#6

Why do we not do rev==true ?


#7

Thank you for the thorough explanation. Although I would disagree that "the exercise requires you to do so" — the exercise made no mention of needing to add a return statement. It just said to add an if statement.


#8

Why does it require a return, when the array is modified in place? We can still access the modified array after methods completion without the return, cant we?