Reputation: 45941
When working in C#, I found it very convenient to create extension methods. In Ruby, one might look like:
class Fixnum
is_divisible? divisor
self % divisor == 0
end
end
But I don't see people extending built in types in this way.
The non-extension way would be:
def is_divisible? dividend, divisor
dividend % divisor == 0
end
It seems to me that the second way is harder to read (is_divisible?(i, 5)
) vs. i.is_divisible? 5
. Or even, i.is_divisible_by? 5
.
Is there a more eloquent Ruby-esque way to do this sort of thing? Or is the first method the preferred way?
Upvotes: 4
Views: 3157
Reputation: 22375
While this is a somewhat trivial example, monkey patches are generally fine. Better to have the method in the class's namespace than floating around in the middle of nowhere.
Just bear in mind that if you're writing a gem or something that you intend other people to use, your monkey patches have a chance of interfering with their monkey patches.
For a simple case like this, it's probably better to avoid it just to be safe.
Upvotes: 4