Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: divisible by 4

Tags:

ruby

modulo

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?

like image 608
snowangel Avatar asked Jan 11 '12 10:01

snowangel


People also ask

What does '%' mean in Ruby?

It gives the remainder when counter is divided by 2. For example: 3 % 2 == 1 2 % 2 == 0.

Which operator will be used to check whether X Y is divisible by 10?

The modulus operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by another—if x % y is zero, then x is divisible by y. Also, you can extract the right-most digit or digits from a number. For example, x % 10 yields the right-most digit of x (in base 10).


1 Answers

Try this:

if i % 4 == 0 

This is called the "modulo operator".

like image 126
Sergio Tulentsev Avatar answered Sep 24 '22 03:09

Sergio Tulentsev