In Progress
Unit 1, Lesson 21
In Progress

Even And Odd

Video transcript & code

So we've got a list of things, and we want to divide them up evenly between two buckets. An easy way to do this is to look at the current index and put items in one bucket if it's an even number, and the other bucket if it's odd.

bucket_a = []
bucket_b = []

[:thing1, :thing2, :thing3, :thing4].each_with_index do |thing, i|
  if ...
    bucket_a << thing
  else
    bucket_b << thing
  end
end

Now, I don't know about you but having tested if numbers were even or odd in many different languages going all the way back to C, the formula is ingrained in my head to the point that it's practically muscle memory: divide the number by two and see if the remainder is zero or not. Or, in Ruby terms, number modulo two equals zero:

i % 2 == 0

Unfortunately, no matter how many times I type this idiom, when I read it back it just doesn't scream out that it's checking to see if a number is even or odd.

I was recently reminded this is not the idiomatic way to check for even- or odd-ness in Ruby. Since everything is an object, we can simply ask the integers if they are even or odd:

2.even?                         # => true
2.odd?                          # => false

This is much more readable as the basis for our equitable distribution algorithm:

bucket_a = []
bucket_b = []

[:thing1, :thing2, :thing3, :thing4].each_with_index do |thing, i|
  if 
    bucket_a << thing
  else
    bucket_b << thing
  end
end

I realize that this is probably old hat for some viewers. But for those of you who, like me, sometimes slip into old habits: I hope this is a helpful reminder of how Ruby's rich numeric classes can make code read more expressively. Happy hacking!

Responses