Is the keyword unless
the same as if
?
When do you use ?
?
I've seen:
if someobject?
I know it checks against nil correct?
Is the keyword 'unless' the same as 'if' ?
No, it's the opposite.
unless foo
is the same as if !foo
if someobject?
I know it checks against nil correct?
No it calls a method named someobject?
. I.e. the ?
is just part of the method name.
?
can be used in methodnames, but only as the last character. Conventionally it is used to name methods which return a boolean value (i.e. either true or false).
?
can also be used as part of the conditional operator condition ? then_part : else_part
, but that's not how it is used in your example.
unless
is actually the opposite of if
. unless condition
is equivalent to if !condition
.
Which one you use depends on what feels more natural to the intention you're expressing in code.
e.g.
unless file_exists?
# create file
end
vs.
if !file_exists?
# create file
end
Regarding ?
, there is a convention for boolean methods in Ruby to end with a ?
.
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