2

I have a method that contains the following code.

def save_question(content)

  question = Question.new

  question.content = content

  question.save

end

When I run this in an if statement

if save_question(content)
  puts "Everything is cool"
else
  puts "Something went wrong"
end

The method returns "Everything is cool". However if I change the method to this

def save_question(content)

  question = Question.new

  question.content = content

  return false unless question.save

end

Then the if statement will return "Something went wrong". Am I missing something big here? I thought the save method returns true, which is does, but why does the method return false?

1 Answer 1

6

You're modifying your method so that it returns false or nil, which is also falsy.

Your last line now reads

return false unless question.save

There is no implicit return true here. If question.save returns true, the return false is never executed, and the expression evaluates to nil.

Think of it this way: What would you expect this version of the function to return?

def save_question(content)
  if !question.save
    return false
  end
end
4
  • 1
    pants -> false. That's an interesting typo :) May 23, 2013 at 17:05
  • I was going to make some point about "just because you're returning false doesn't mean the there's an implicit opposite return true; what if you return some arbitrary thing like "pants"", but decided it was a mixed message :p
    – user229044
    May 23, 2013 at 17:06
  • Ahhh. I get it now. Silly second part question then would be what's a Ruby way to keep the method continue on if save returns true and I have more code below the save method?
    – thank_you
    May 23, 2013 at 17:08
  • @jason328 I'm not sure what you mean. You'd just keep adding code afterwards, there's nothing wrong with doing so.
    – user229044
    May 23, 2013 at 17:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.