Ruby ternary operator without else
a.action if object.method?
ternary operator based on if else
For something like this you might want to use a simple look-up table to eliminate some of the logic:
EQUIVALENT = {
'Y' => 'guest',
'N' => 'test'
}
if (a.present?)
b = EQUIVALENT[b.value] || b
end
The || b
part may not be necessary if non-mapped b
values are ignored.
Using defined? in a Ternary operator
It should be:
<% defined?(foo) == "local-variable" ? foo : nil %>
From documentation
:
... return value provides information about the expression.
>> defined?(foo) == "local-variable"
=> true
>> defined? foo
=> "local-variable"
>> defined? (foo == "local-variable")
=> "method"
Ruby operator precedence
Ruby ternary operator if else
@skill = @user.skill || Skill.new
If the value of @user.skill if nil, it will asign the next value( Skill.new) to @skill.
How can I use the ternary operator with multiple values?
Since a ternary operator is exactly that (an operator), you can't split it over multiple instructions.
However, blocks make it possible to "squash" multiple instructions into a single expression.
def my_withdraw(pin_number,amount)
puts (
pin_number == @pin ?
begin
@balance -= amount
"Withdrew #{amount}."
end :
pin_error
)
end
Of course, this is completely illegible and I would never recommend you use that sort of syntax in the real world. But for the sake of science, why not.
DRY up Ruby ternary
Assuming you're okay with false
being treated the same way as nil
, you use ||
:
PROFESSIONAL_ROLES.key(self.professional_role) || 948460516
This will return 948460516
if key
returns nil
or false
and the return value of the call to key
otherwise.
Note that this will only return 948460516 if key
returns nil
or false
, not if it returns an empty array or string. Since you used nil?
in your second example, I assume that's okay. However you used blank?
in the first example (and blank?
returns true
for empty arrays and strings), so I'm not sure.
replace ternary nil check with ruby best practices
The usual pattern is:
result = method(args) || default_value
The ||
operator is short-circuiting. If the left-hand-side is true, it will not bother to evaluate the right hand side. In Ruby, nil
is considered false. Hence if nil
is returned (or false
), the ||
evaluates the right-hand-side and returns that as the result.
Note the order of the left and right sides is important.
Ruby Assigning True and False strings?
Use an inline if
or a ternary if operator
:
shopping_list = {
"milk" => false,
"eggs" => false,
"jalapenos" => true
}
puts "Here is your Shopping List:"
shopping_list.each do |key, value|
puts "#{key} - #{if value then 'purchased' else 'not purchased' end}"
# or this:
# puts "#{key} - #{value ? 'purchased' : 'not purchased'}"
end
Prints:
Here is your Shopping List:
milk - not purchased
eggs - not purchased
jalapenos - purchased
Which operator to use: ternary operator (?:
) or if/then/else/end
?
I chose here if/then/else/end
, but listed both options as acceptable. It is a matter of style which one you choose.
Some Stack Overflow Ruby users prefer to use a regular if ... then ... else ... end
. It is longer, but more clear and more idiomatic. See, for example, these answers:
https://stackoverflow.com/a/2175392/967621
https://stackoverflow.com/a/4253250/967621
Other Stack Overflow users prefer ?:
, which is more concise and clear, if you are used to it. Also note that The Ruby Style Guide agrees:
Prefer the ternary operator(
?:
) overif/then/else/end
constructs. It’s more common and obviously more concise.
# bad
result = if some_condition then something else something_else end
# good
result = some_condition ? something : something_else
Is the ternary operator ?: defined as a method in Ruby?
Is the ternary operator in Ruby really just a syntactic sugar for if ... then ... else ... end statements?
Yes.
From doc/syntax/control_expressions.rdoc
You may also write a if-then-else expression using
?
and:
. This ternary if:input_type = gets =~ /hello/i ? "greeting" : "other"
Is the same as this
if
expression:input_type =
if gets =~ /hello/i
"greeting"
else
"other"
end
"According to this book, "every operation is a method call on some object and returns a value." In this sense, if the ternary operator represents an operation, it is a method call on an object with two arguments."
if
, unless
, while
, and until
are not operators, they are control structures. Their modifier versions appear in the operator precedence table because they need to have precedence in order to be parsed. They simply check if their condition is true or false. In Ruby this is simple, only false
and nil
are false. Everything else is true.
Operators are things like !
, +
, *
, and []
. They are unary or binary. You can see a list of them by calling .methods.sort
on various objects. For example...
2.4.3 :004 > 1.methods.sort
=> [:!, :!=, :!~, :%, :&, :*, :**, :+, :+@, :-, :-@, :/, :<, :<<, :<=, :<=>, :==, :===, :=~, :>, :>=, :>>, :[], :^, :__id__, :__send__, etc...
Note that in Smalltalk, from which Ruby borrows heavily, everything really is a method call. Including the control structures.
Related Topics
Check If a Constant Is Already Defined
Difference Between Resource and Resources in Rails Routing
Before/After Suite When Using Ruby Minitest
Rack::Request - How to Get All Headers
Rails Put Validation in a Module Mixin
Nested Forms in Rails - Accessing Attribute in Has_Many Relation
How to Traverse Symlinked Directories in Ruby with a "**" Glob
Elasticsearch & Tire: Using Mapping and To_Indexed_JSON
Generate an HTML Table from an Array of Hashes in Ruby
Is There an Equivalent Null Prevention on Chained Attributes of Groovy in Ruby
Form_For "First Argument in Form Cannot Contain Nil or Be Empty" Error
Trouble Yielding Inside a Block/Lambda
Editing Existing Rails Migrations Is a Good Idea
Error Installing Ruby with Rvm (Osx 10.8)