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


#1



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


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)


#2

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

#3

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 (.


#4

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