# Should `divisible_by?` be preferd over `x % y == 0`?

I see quite regularly the use of `x % y == 0` but some may argue that `divisible_by?` adds readability to code and shows the intent of what the operation is being done. Thereby I wonder if one is preferred over the other in certain situations or if it doesn’t matter from a language perspective which to use?

From a language perspective it doesn’t matter as both are quite readable, but there are cases where you’d want to use the former over the latter (for example, using the modulo result in further calculations).

I’d prefer `divisible_by?` because it clearly describes the intent.

As a bonus it should also be a tiny bit more performant. This probably doesn’t matter much unless you do loads of operations in which case you might want more specialized code anyway.

But that would not be a use case for `x % y == 0`. Only for `x % y` which isn’t asked here.

8 Likes

`0.divisible_by?(0)` should be true even when `0 % 0` is undefined, because there exists an integer `n` such that `0 * n == 0`. Currently this is how `BigInt` defines it

should be true

That depends on what definition of divisibility that is used. Not allowing m to be 0 is pretty common. See discussion in the defintion part of Divisor - Wikipedia .

The problem is that 0*n == 0 for all n, so it is pretty pointless. Especially as `divisor` typically means a division can be done, which is not the case here. I’d be quite surprised if I found 0 to be the divisor of anything, as it cannot divide anything by definition.

What straight-shoota said. Just as I prefer `array.empty?` over `array.size == 0`, for the same reason. Remember, you’re not writing for the compiler, but for the next developer (and often yourself). Make the intent clear rather than the implementation.

6 Likes