Video transcript & code
OK, today we've got a real quickie. In episode #347 we were extracting a page number and offset from absolute indexes. For instance, let's say the absolute index is 42, and the page size is 10. In order to get the page number, we divide the index by the page size. And in order to get offset, we do the same thing again. Only this time, we use the modulo operator to take the remainder instead of the quotient.
index = 42 page_size = 10 page = index / page_size # => 4 offset = index % page_size # => 2
Now this is the kind of code that is reasonable, clear, and yet it drives a tiny part of my brain absolutely nuts.
Why? Because we do the same division operation twice.
Does this matter? No, it almost certainly doesn't. Only if this code were at the heart of some serious number-crunching logic could this doubled operation possibly matter from a performance standpoint.
But it still bothers me.
Thankfully, there is Ruby a method just for people like me. Instead of using the division and modulo operators, we can use the
#divmod method. This method performs the division, and then returns both the quotient and the remainder as an array of two items. Through the magic of Ruby's destructuring assignment, we can assign these directly to a pair of variables.
index = 42 page_size = 10 page, offset = index.divmod(page_size) # => [4, 2] page # => 4 offset # => 2
And that is literally all I wanted to show you today. If you ever need to do a division and you need to use both the quotient and the remainder,
#divmod is arguably the more idiomatic way to go about it. And if you're like me and you just can't stand that repeated operation, it's a lot more satisfying than the two-line version. Happy hacking!