Search code examples
ruby-on-railsruby-on-rails-4

Easiest way to find divisors of 60 in Ruby on Rails


Other than hardcoding or using the Math module, Is there any way I can find divisors of 60 in Ruby on Rails. Any helper methods/regular expression that I can make use of? Thanks for your help.


Solution

  • One of the easiest ways to achieve this would be to create a list of numbers between 1 and 60, and then only select the ones that divide 60 with no remainder.

    To expand on SteveTurczyn's answer, we can do:

    (1..60).select { |n| 60 % n == 0 }
    

    The (1..60) part creates an enumerator (which in this case we can think of as an array of the numbers between 1 and 60).

    Then you want to take this array, and select only the elements are divisors of 60.

    We can use the modulus operator %, which gives us the remainder left over when we divide a number by another (e.g., 5 % 2 returns 1). Of course, if there is no remainder, then we know that the number divided cleanly, and is therefore a divisor of that number (i.e., if a % b == 0, then b is a divisor of a).

    So what we want to do, is use the above as a criteria for selecting elements out of the array of numbers between 1 and 60, which we are able to do with the Array#select method.

    If we have something, like an array (technically, I think, an Enumerable), we can use #select and a block to pull out only the elements that satisfy whatever criteria we specify in the block.

    The { |n| 60 % n == 0 } is the block we are passing to #select, which will return true whenever 60 % n is 0 (each n is an element from the array of numbers 1 through 60). Array#select only returns the elements in the array for which the block evaluates to true- which is how SteveTurczyn's solution works.