Method doesn't Default to Alphabetize an Array


#1

Help -- I'm going nuts trying to figure out what's wrong with my code for this section:

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

It works perfectly in the command window - it will sort an array and reverse it if rev is included as a parameter - but I consistently get the message "It looks like your method doesn't default to alphabetizing an array when it doesn't receive a second parameter". Anyone know why this is? I also tried this simpler permutation:

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

It works just as effectively, but I still get an error message.


#2

The term 'default' usually refers to an else statement, since that is the default action in a conditional branch.

if rev
    arr.reverse!  # this is a reverse sort so don't sort beforehand
else
    arr.sort!
end

Outside of the method we cannot refer to local variables from its scope. We need to puts the return value.

puts "A-Z: #{alphabetize(my_array)}"

puts "Z-A: #{alphabetize(my_array, true)}"

The above assumes my_array is defined and populated with data.


#3

Ok that makes sense. I have 2 further questions:

  1. Is putting the "default" process within an else statement necessary for the program to run, or just good programming practice? It seems like the code should work even if you flip the if/else processes

  2. I understand that outside of the method you cannot call on a local variable, but my "puts arr" line is within the alphabetize method. I was able to get rid of the error message by displaying the variables as you suggested, but I don't understand why my original code didn't work. If I defined the array as "arr" within the method, and used "puts" to display it within the method, why should that result in an error message?


#4
  1. It is the author's choice in this instance to make the forward sort the default action. It otherwise wouldn't matter so long as the branch outcome is as expected. The above way was simple and easy with minimum code.

  2. You are right about arr being in the same scope (had Python on the brain). That wouldn't raise an exception. However the SCT is written to examine the exercise, not the syntax. It expects the puts statement to be outside of the method.