Ruby: divisible by 4

snowangel picture snowangel · Jan 11, 2012 · Viewed 63.8k times · Source

This works fine, but I want to make it prettier - and accommodate all values that are divisible by 4:

if i==4 || i==8 || i==12 || i==16 || i==20 || i==24 || i==28 || i==32
  # ...
end

Any clever, short method to do this?

Answer

Sergio Tulentsev picture Sergio Tulentsev · Jan 11, 2012

Try this:

if i % 4 == 0

This is called the "modulo operator".