What does the % operator do in Ruby in N % 2?

后端 未结 9 1949
甜味超标
甜味超标 2021-02-02 09:57

if counter % 2 == 1 I am trying to decode this line - it\'s a Rails project and I am trying to figure out what the % does in this if statement.

9条回答
  •  时光取名叫无心
    2021-02-02 10:21

    Regardless of how it works, the modulo operator is probably not the best code for the purpose (even though we are not given much context). As Jörg mentioned in a comment, the expression if counter.odd? is probably the intent, and is more readable.

    If this is view code and used to determine (for example) alternating row colors, then you may be able to do without the counter altogether by using the built-in Rails helper cycle(). For example, you can use cycle('odd','even') as a class name for a table row, eliminating the counter and surrounding if/then logic.

    Another thought: if this is within an each block, you may be able to use each_with_index and eliminate the extraneous counter variable.

    My refactoring $0.02.

提交回复
热议问题