5/6 If statement. What for?


#1

Could you please clarify what actually do the if statement at the code below?

Asking because the code works similar with and without if statement


#2

Hi, first some proper formatting would be great:

# A method with a default argument for rev
# If the user calls the function giving only one argument (arr),
# rev will be taken to be false
# Otherwise, it will take whatever the user passed as argument
def alphabetize(arr, rev = false)

  # Sorts the given array (modifies original)
  arr.sort!

  # Checks whether rev is true
  if rev == true
    arr.reverse! # Reverse array if argument rev is true
  else
    arr # Do not reverse because rev is false
  end

end

numbers = [5, 4, 3, 2]
# Here you are calling your method using only one argument.
# That will be taken as the array
# Because you did not provide the second argument, which will be taken as rev,
# Ruby will use the default argument provided in your method definition
# above. Therefore, rev will be false whenever there are no arguments passed.
alphabetize(numbers)
puts numbers

Now you understand why taking out the if doesn't matter? Because rev will always be false if you do not pass the second argument to the alphabetize method.


#3

Thanks! Now I understand
Could you please provide an example with second argument based on my example?


#4
numbers = [2, 5, 3, 8]
alphabetize(numbers, true)
print numbers
puts

Output:
[8, 5, 3, 2]


Previous one (not reversed):

numbers = [5, 4, 3, 2]
alphabetize(numbers)
print numbers
puts

Output:
[2, 3, 4, 5]