5. Sorting with Control flow


#1

Hi there,

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

numbers = [3, 1, 67, 14, 0]

puts alphabetize (numbers)

My code above passes and gives me the right output however if I change the last line from puts alphabetize (numbers) to puts alphabetize (numbers, true), I get the error:
(ruby):12: syntax error, unexpected ',', expecting ')'
puts alphabetize (numbers, true)
^
My intention of changing the last line is just to try print the numbers array sorted and reversed, but as mentioned I just get the error.

Thanks heaps


#2

I think it's simply because it didn't ask you to, so the developers created their testing accordingly. Maybe someone else can correct me?


#3

Hmm I'm not sure that is the case given the error message :S


#4

I think ur rite, if u run this on ur local machine should be fine.


#5

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

The issue is white space.

puts alphabetize(numbers, true)
# no space here^

Also,

Should be,

    if rev == true
        arr.reverse!
    end
    return arr

Your code is not returning the array when rev==true.


#6

Indeed, that else statement was totally redundant


#8

Quick question: I noticed "return arr" is needed now in this step. In the previous step, when we applied the .sort! method, it wasn't necessary. Also, it wasn't needed after the if/else statement in the first step showing what we'll build. Confusing. Thanks.


#9

Some of the steps are intermediate and won't actually run to completion. The SCT just checks for the code and lets us move forward if the expected code is there. It is not a exhaustive check, and usually lets a lot of stuff by that should not be allowed. Such is the nature of limited checking.

The big ones to watch are interpreter/compiler errors given in the console. That is Ruby talking, and those errors (even when allowed to pass) should be read, studied and resolved so one learns about the error, what causes it and how to fix it.


#10

A post was split to a new topic: Does anyone have any improvement suggestions?


#11

Ah.. good to know. Thanks!


#12

A post was split to a new topic: Can someone tell me what's wrong with this code


#14