Reputation: 817
Why does the following code fail to produce expected output, for the first two test cases if I don't add the "then" section to the the 'If?' I set the default value of the second variable "False" and I was under the impression that in Ruby a method could take an unspecified number of parameters, and the lack of a parameter when the method is called will roll back to using the default values of that parameters within the method if set.
def alphabetize(arr,rev=false)
arr.sort!
if rev == true
arr.reverse!
end
end
numbers = [1,9,2,1,10]
Test cases:
print alphabetize(numbers,false)
=begin
input: numbers,false
output: nil
expected output: 1,1,2,9,10
=end
print alphabetize(numbers)
=begin
input: numbers
output: nil
expected output 1,1,2,9,10
=end
print alphabetize(numbers,true)
=begin
input: numbers,true
output: 10,9,2,1,1
expected output: 10,9,2,1,1
=end
This code produced the expected results:
def alphabetize(arr,rev=false)
if rev == true
arr.sort!.reverse!
else
arr.sort!
end
end
numbers = [1,9,2,1,10]
Upvotes: 1
Views: 65
Reputation: 13
def alphabetize(arr,rev=false)
arr.sort!
if rev == true
arr.reverse!
end
arr
end
Upvotes: 0
Reputation: 1022
You are printing the return value of the alphabetize
method, which is not necessarily the value of the array.
In your first code, you have an if
without a corresponding else
as the last statement. In Ruby, the return value of an if
statement without an else is nil
, when the if
condition fails.
In your second code, you have an if
with an else
statement. So the return value of the method, when the if
condition fails, will be what gets executed inside the else
block. In this case, arr.sort!
.
It's worth mentioning the alphabetize
method modifies the numbers
array being passed in (indicated by the !
in the sort!
and reverse!
methods). If you printed numbers
, instead of return value of alphabhetize
, you would have the expected output as well.
Upvotes: 2