Reputation: 45
Will I run into any problems using a statement like this:
options[:discount] ? "Does something if true" : nil
Instead of:
"Do something if true" if options[:discount]
I'm not sure I would actually use the former syntax, but I am interested if returning nil
in such a statement would cause any issues. Just trying to learn more about Ruby's structure and this was an interesting question to me. Thanks for any insight!
Upvotes: 1
Views: 864
Reputation: 7223
One difference is the precedence of those two operators. Consider the following:
options = {discount: false}
prexisting_value = "prexisting value"
using the first expression, you get this:
prexisting_value = options[:discount] ? "Does something if true" : nil
p prexisting_value
=> nil
using the second expression, you get this:
prexisting_value = "Do something if true" if options[:discount]
p prexisting_value
=> "prexisting_value"
this happens because the two examples are parsed differently (note the location of the parenthesis):
prexisting_value = (options[:discount] ? "Does something if true" : nil)
vs
(prexisting_value = "Do something if true") if options[:discount]
Upvotes: 1
Reputation: 27885
It may depend how you use it.
Let's try it with
options = {
:discount => true
}
x = options[:discount] ? "Does something if true" : nil
y = "Do something if true" if options[:discount]
p x
p y
and you get
"Does something if true"
"Do something if true"
With the false
-value, you get two times nil
.
If you want to print the result immediate, without an additional variable like in
p options[:discount] ? "Does something if true" : nil
p "Do something if true" if options[:discount]
you get the same result for true
, but with false
you get only one nil
.The if
-clause is used for the complete expression p "Do something if true"
.
Or another example:
You can use the ternary operator as a parameter:
def my_method(par)
p par
end
my_method(options[:discount] ? "Does something if true" : nil)
but you get syntax error, unexpected modifier_if, expecting ')'
with
my_method("Do something if true" if options[:discount])
You can use the if
with two braces:
my_method(("Do something if true" if options[:discount]))
or you use
my_method(if options[:discount]; "Do something if true";end )
Upvotes: 3