5. Sorting with Control Flow/ Code works, but don't understand

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/en/courses/ruby-beginner-en-nOho7/0/5?curriculum_id=5059f8619189a5000201fbcb

<In what way does your code behave incorrectly? Include ALL error messages.>
So my code works and passes fine, I understand what it’s doing.

But, unless I’m misunderstanding the instruction, my code should output the numbers in reverse order, but they are coming out as ascending order. Since the argument makes rev==true, why isn’t it printing out in reverse?

```

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

numbers = [9, 94, 81, 31, 22]

puts alphabetize (numbers)

<do not remove the three backticks above>
1 Like

In absence of a second argument true the function defaults to false. To reverse the order include the second argument in the call.

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

numbers = [9, 94, 81, 31, 22]

puts alphabetize(numbers)
puts
puts alphabetize(numbers,true)

Output

9
22
31
81
94

94
81
31
22
9
1 Like

In absence of a second argument true the function defaults to false. To reverse the order include the second argument in the call.

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

numbers = [9, 94, 81, 31, 22]

puts alphabetize(numbers)
puts
puts alphabetize(numbers,true)

Output

9
22
31
81
94

94
81
31
22
9

This will raise a syntax error when two arguments are passed in. Remove the space character before (.

2 Likes

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