So, I have this code from a colleague with lots of return false
and return true
.
For example this method:
def has_only_one_uploaded_image?
return false if images.size > 1
method_here
end
If I remove the false
as the return value, will it still work if I use it from other conditions?
like in this method...
def commission_plan_product_available?
(has_only_one_uploaded_image? ||
(has_many_images? && images_are_saved?))
end
I'm confused as to when to use the proper boolean
return and when I should not.
I'm new to Ruby (not sure if nil
can be also false
in conditionals, please bear with me. Thank you.
Can someone shed some light please?
if false or if nil won't execute the corresponding condition, because false and nil are considered as falsy values. In other words, if you cast nil or false as a boolean, it will return false . Every other kind of value is considered truthy in Ruby.
Every object in Ruby has a boolean value, meaning it is considered either true or false in a boolean context. Those considered true in this context are “truthy” and those considered false are “falsey.” In Ruby, only false and nil are “falsey,” everything else is “truthy.”
In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass.
nil
is "falsey", and if used directly in a conditional - or combined using logical operators &&
, ||
etc, will behave the same as false
, and your uses of it should work as you intend.
However, it is usually better practice to return true
or false
values from methods that behave like booleans. There is little or no extra cost, true
and false
are the same sort of thing internally to Ruby as nil
(a simple VALUE with fixed content, it is not resolved as a pointer).
Returning nil
conditionally makes more sense when you have a method which either returns an object you have asked for, or "nothing" for some good reason (e.g. you ask for a User with a specific id, but there is no such User).
If in doubt, think of how you would document the method. If you would need to explain to a user why it returns true
or nil
, and the explanation for this choice seems convoluted, then it would be much simpler to do what is expected and return true
or false
For a very few methods, it may even make sense to return true
, false
or nil
- the last one being essentially "I don't know". A method that caches the output from another method that returns true
or false
might do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With