5/6 If statement. What for?


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


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)

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


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


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

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

[8, 5, 3, 2]

Previous one (not reversed):

numbers = [5, 4, 3, 2]
print numbers

[2, 3, 4, 5]