问题
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?
回答1:
Try this:
if i % 4 == 0
This is called the "modulo operator".
回答2:
There's also modulo
, which allows you to do
420.modulo(4).zero?
There's nothing stopping you doing that with %
, but it looks weird:
420.%(4).zero?
回答3:
This is always a good conversation starter:
if (i & 3).zero?
来源:https://stackoverflow.com/questions/8817927/ruby-divisible-by-4