How do I convert boolean values to integers?

后端 未结 7 1066
日久生厌
日久生厌 2020-12-16 10: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
  inflectio         


        
相关标签:
7条回答
  • 2020-12-16 10:58

    Here's another method:

    5 - bool.to_s.length

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

    0 讨论(0)
  • 2020-12-16 10:59

    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 讨论(0)
  • 2020-12-16 11:03
    inflection_point = (firm.inflection_point ? 1 : 0)
    
    0 讨论(0)
  • 2020-12-16 11:04

    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
    
    0 讨论(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)

    0 讨论(0)
  • 2020-12-16 11:13

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

    0 讨论(0)
提交回复
热议问题