Why does puts not work the same?


#1

link: https://www.codecademy.com/courses/learn-ruby/lessons/methods-blocks-sorting/exercises/practice-makes-perfect-1?action=resume_content_item

(MY CODE:)

def by_three?(num)
  if num % 3 == 0
    puts true
  else
    puts false
  end
end

(SOLUTION:)

def by_three?(num)
  if num % 3 == 0
    return true
  else
    return false
  end
end

For this code I was asked to “Define a by_three? method that takes a single integer parameter, number , and returns true if that number is evenly divisible by three and false if not”. My main question is why do I have to use return here? Why does puts not work the same?
Thank you


#2

puts and return are very different, puts prints output while return hands data back to the function call


#3

so the code keeps going after the puts prints output but for return it ends the code there and goes back to the function call?


#4

but in this case wouldn’t the outcome be the same?


#5

return hands back to the function call

no, because when using return this:

by_three?(5)

won’t give any output given you wont print the returned result:

puts by_three?(5)

furthermore, if return is not explicitly used, the function will return a default value.


#6

Ruby is different from python there, everything is an expression and the result of a function is whatever the body evaluates to (the return keyword can therefore sometimes be omitted, and this is one such case)


@josephspinelli210164 there is no overlap between puts and return


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.