"Ordering Your Library" "Sorting with Control Flow" error


#1

https://www.codecademy.com/courses/ruby-beginner-en-nOho7/0/5

So I have this in the console:

nil

and Codecademy says this:

and this is my code:

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


What's wrong with it?


#2

Hello @printcoder_eric,

You haven't returned anything from the function. Your should have an if else statement like so...

if rev
    return something
else
    return somethingelse
end

That's how you pass this exercise. Hope this clears it out for you...


#3

@bartholomewallen
I tried this:

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

and it worked.


#5

Try this:

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

numbers = [5, 1, 3, 8]

puts alphabatize(numbers)

While the alphabetize method takes two parameters when we define it, the second one is a boolean and is only optional. Thus, the method is (simply at this point in the lesson) defined by arr.sort!, which means you don't need the if/else statement because you've got arr.sort! already.


#6

Following the instruction stated to placing the IF statement after the arr.sort!. the right flow should be like this. Since the arr already sorted outside the IF statement we only call the arr in ELSE statement.

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

#7

I agree with you, and there is no need to use "return" in this code.


#8

the simpest is the better. Check tthis out:

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

numbers =[5, 6, 8, 2, 1, 7]
alphabetize(numbers)

puts numbers