39

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
  inflection_point = 1
else
  inflection_point = 0
end
1

8 Answers 8

74
inflection_point = (firm.inflection_point ? 1 : 0)
0
28

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
0
24

If you just have that at one point, then rudolph9's answer is good, but if you are having a similar kind of logic all over the place, then maybe it might make sense with general use in mind to monkey patch:

class FalseClass; def to_i; 0 end end
class TrueClass; def to_i; 1 end end

inflection_point = firm.inflection_point.to_i

Within Ruby, you should keep all of your logic dealing with truth values rather than 0 and 1, but I guess you are dealing with some inputs or outputs from/to some external system that deals with 0 and 1. Then, doing like this will make sense.

3
  • 1
    Adding to my personal library. Sometimes I have a series of comparisons or other logical tests I need to assemble together into one bitfield.
    – Marcos
    Jan 29, 2013 at 19:31
  • 4
    The problem is that 0 == true so this might create a lot of confusion to someone who is going to support your codebase.
    – Andrew
    Mar 29, 2013 at 11:21
  • Monkey patching base core classes for such a simple thing is a very bad idea. You can catch some bug from a gem which does not expect to have such a method on true/false objects.
    – criskiev
    Apr 29, 2019 at 12:47
8

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
5

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)

4
  • 5
    First off: it's called the conditional operator, not the ternary operator. Saying "the ternary operator" doesn't even make sense, there's an infinite number of ternary operators. Secondly, you don't need the conditional operator in Ruby. You need it in "almost every other language" because in those languages if is a statement. But Ruby doesn't have statements, it only has expressions and thus if is an expression as well. Nov 24, 2012 at 13:36
  • 5
    From The Ruby Programming Language, by D. Flanagan & Y. Matsumoto 4.6.10 Conditional: ?: The ?: operator is known as the conditional operator. It is the only ternary operator (three operands) in Ruby. The first operand appears before the question mark. The second operand appears between the question mark and the colon. And the third operand appears after the colon. You'd better write to these guys and tell them to correct their book. Nov 25, 2012 at 1:52
  • 2
    @thebugfinder The book is correct: it is called the conditional operator. Which is actually the point that @JörgWMittag is making. `` It may be the only ternary operator Ruby offers, but that does not make "the ternary operator" the correct name for it. Dec 14, 2016 at 1:41
  • 3
    I'd argue if there is one apple on the desk it is "the apple" if there is sun in the sky it is "the sun".. if its the only ternary operator in the code it is "the ternary" It is also "A" ternary. I mean if we are being pedantic about vocab.
    – baash05
    Feb 2, 2017 at 23:21
4

It is not pure ruby solution but, You can use ActiveRecord::Type::Integer.new.cast(true)

3

I just noticed a lot of people proposed to Monkey Patch the ruby classes and implement the .to_i method on them in order to solve this problem.

I need to gently inform that the act of Monkey Patching the TrueClass and FalseClass can be dangerous to your system

A good approach is to use the Ruby Refinements in order to make a much safer monkey patching. This approach restrict the changes on the monkey patched classes to the scope of your class.

  • lib/refinements/boolean_refinements.rb
module BooleanRefinements
  refine FalseClass do
    def to_i
      0
    end
  end

  refine TrueClass do
    def to_i
      1
    end
  end
end
  • /your_class.rb
require 'refinements/boolean_refinements'

class MyClass
  using BooleanRefinements

  # Here you can use true.to_i and false.to_i as you wish
end
1

Here's another method:

5 - bool.to_s.length

This takes advantage of the fact that 'true' has four characters, while 'false' has 5.

4
  • 9
    This technically will work but it's convoluted and has a really bad code smell.
    – rudolph9
    Mar 13, 2017 at 17:33
  • 1
    Yeah, but at least it won't increase your cyclomatic complexity like the ternary versions will. It's all about mitigating metrics. Mar 13, 2017 at 19:31
  • 4
    It would in increase the cyclomatic complexity by 1. Ruby is a very dynamic language and should inflection_point be nil this is not going to work (putting conditionals on something that might be nil is common in ruby). I see where you're coming from but in practice it doesn't make sense.
    – rudolph9
    Mar 14, 2017 at 16:15
  • 4
    Not a good practice… but I must admit it looks interesting. :D
    – gnclmorais
    Jun 21, 2017 at 14:00

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.