Reputation: 11107
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?
Upvotes: 2
Views: 1076
Reputation: 239402
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
Upvotes: 6