I have a boolean value to check if it is true, then set a local variable. How do I refactor this so it is more Ruby-ish?
if firm.inflection_point
inflectio
Here's another method:
5 - bool.to_s.length
This takes advantage of the fact that 'true'
has four characters, while 'false'
has 5.
Another alternative is use of short-circuit operators:
inflection_point && 1 || 0
irb(main):001:0> true && 1 || 0
=> 1
irb(main):002:0> false && 1 || 0
=> 0
inflection_point = (firm.inflection_point ? 1 : 0)
In Ruby, if
is an expression. There's no need to assign to a variable inside the then
and else
branches, just return the value you want and assign the variable to the result of the if expression
:
inflection_point = if firm.inflection_point
1
else
0
end
In simple cases like this, it's more readable to write the entire expression on a single line:
inflection_point = if firm.inflection_point then 1 else 0 end
You can also use the conditional operator, which I personally find to be much less readable:
inflection_point = firm.inflection_point ? 1 : 0
What you need is a conditional operation that is known as Ternary Operator It's used in almost every language and it uses the symbols ? and :
inflection_point = firm.inflection_point ? 1 : 0
basically means, if the first condition evaluates to true (firm.inflection_point), return the value after "?" (1) otherwise, return the value after ":" (0)
It is not pure ruby solution but, You can use ActiveRecord::Type::Integer.new.cast(true)