Rest of division in ruby

Asked

Viewed 113 times

-3

I have a array of values:

values = [2, 7, 15, 11, 5]

I would like to take only the values that divide between them give rest '0' (return 15 and 5).

I’m getting it this way, but the code will read others arrays of numbers that are not divisible by 5, then each division would have to be made within the array, for each other.

values.select{|num| num % 5 == 0}

I would like to receive the same result but not using divisor number (5) in the case.

[15, 5]
  • what you already have of code?

  • I resolved in the form below, after taking a look at the documentation, I made a loop nested to another.

3 answers

1

I got it solved like this

resultado =[]
values.map do |num1|
   divisor = values.select{|num2| num1 % num2 == 0}
resultado << divisor
end
resultado.inject(:+)

I made a noose inside of another to get the values.

0

Hi, I took the opportunity to make my implementation to practice.

values = [2, 7, 15, 11, 5, 30]

new_values = []

values.each {|x| values.each {
 |y| (x % y == 0) and (x != y) ? new_values << x << y : nil }
}


p new_values.uniq

values.each {|x| values.each { |y| (x % y == 0) and (x != y) ? (puts "O resto de #{x} e #{y} = #{x % y}") : nil }}

Your question helped me to learn new concepts. Thank you.

-1

You can try to do it in block too, it gets pretty organized =D

resultado = []
values = [2, 7, 15, 11, 5]

values.each { |num| resultado << num if n % 5 == 0 }

puts resultado

where the each will go through each value in the list values, the variable in a will receive each number/value and will be added to the Array outworking if it meets the condition.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.