Home > Blockchain >  Summing A Defined Previous Loop on Ruby
Summing A Defined Previous Loop on Ruby

Time:06-16

I am attempting to try and sum an array I have created in Ruby. I'm using an integer (10) as an example, but the code must be able to allow any type of integer to be plugged into it. I must plug in a number, & have Ruby find any #'s from 0 to that plugged in number that are divisible by 3 & 5. Numbers should never repeat in the array. Then I need to have those numbers summed. I have created the loop to find those numbers, but my problem is I cannot figure out how to then sum those numbers in the array after. I have googled so many different options, and none have worked. I am very new at this, but I am trying desperately to figure things out. Any help would be much appreciated, thank you.

Here is my code so far, & I know the summing loop doesn't work, but I am showing how I tried:

Attempt #1:

def sum_multiples(num)
  mult = []
  i = 1
  while i < num
    if (i % 3 == 0 || i % 5 == 0)
      mult << i
    end
    i  = 1
  end
  return mult
end

def summing(array)
  array = mult
  sum = 0
    array.each do |x|
    end
  sum  = x
end

puts sum_multiples(10)

Attempt #2:

def sum_multiples(num)
  mult = []
  i = 1
  while i < num
    if (i % 3 == 0 || i % 5 == 0)
      mult << i
    end
    i  = 1
  end
  return mult
end

def summing(array)
    array = mult
        array.each { |a| sum =a }
  return array
end

puts sum_multiples(10)

CodePudding user response:

In your first attempt you have defined a summing method, but you are not using it - which is a good thing because it does not work at all. The good news is that a arrays do have a sum method, so if you change the line return mult to return mult.sum you'll see some progress.

CodePudding user response:

If I understand well what you are attempting to do you can do it easy with the next function:

# sum all numbers from 0 to `num` that are divisible by 3 & 5
# then sum and return the result
# @param num [Integer]
# @return [Integer]
def sum_multiples(num)
  ((0..num).select { |e| (e % 3).zero? && (e % 5).zero? }).sum
end

# we know that all numbers divisible by 3 and 5 are multiples of 15
# so this must print 45
p sum_multiples(30)

Explaining a bit, first we create a range from 0 to the number, and we filter the numbers that we need, then we sum the resulting array.

  • Related