brooklynsweb
brooklynsweb

Reputation: 817

In Ruby Why is the If/Then logic written without the If/Then structure failing?

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

Answers (2)

abhiahirwar
abhiahirwar

Reputation: 13

def alphabetize(arr,rev=false)
   arr.sort! 
   if rev == true
       arr.reverse!
   end
   arr
end
Return array at the end when if false it return nil. To make sure the it returns the array value at the end of method. Tested on rubyfiddle.com http://rubyfiddle.com/riddles/c36bc/1

Upvotes: 0

phss
phss

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 ifcondition 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

Related Questions