Ruby: divisible by 4

微笑、不失礼 提交于 2019-12-31 19:51:21

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!