Adding elements to new array Ruby

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

So initially I m just playing around with the ole FizzBuzz challenge. For those that may be unaware of what this challenge is, allow me to explain. The idea is to print out numbers 1..100 if the number is divisible by 3, it prints Fizz instead of 3; if the number is divisible by 5, it prints Buzz; And if number is divisible by both, it prints FizzBuzz. This is how I performed the challenge:

def super_fizzbuzz(array)  
  array.each do |element|
    if element % 15 == 0 
      puts  FizzBuzz 
    elsif element % 5 == 0
      puts  Buzz 
    elsif element % 3 == 0
       puts "Fizz"
    else 
       puts element
    end
  end
end

This will work as intended. What I am trying to do is have it so the user can put in an array of integers super_fizzbuzz([3,10,15,19]) And have it return the array with the appropriate word replacing the number: [Fizz, Buzz, FizzBuzz, 19]. However, I can t seem to perform this. I have tried the following below, but it only adds the first answer to the array..

super_array = []
array.each do |element|
  if element % 15 == 0 
    super_array[element] <<  FizzBuzz 
  elsif element % 5 == 0
    super_array <<  Buzz 
  elsif element % 3 == 0
    super_array << "Fizz"
  else
    super_array << element
  end

  return super_array
end

My thought process was to create a new array and if the element was divisible by by one or both of the numbers it would place it in the new array, and if it wasn t it would just place the element in the array. What happens when I run it though is that it will just return an array with Fizz. If I run the first code and place the numbers in an array it returns:

Fizz
Buzz
FizzBuzz
19
[3, 10, 15, 19]

Any suggestions would be greatly appreciated.

Answers

return super_array

this statement says "stop everything you are doing and return this value right now"

Therefore the first time through the array, you will get one answer... and then hit this result, and then return this array result without continuing through the rest of the array.

probably what you want is to only return the new "super_array" value after you ve gone through the whole original array... so I d move it to just outside the loop eg:

super_array = []
array.each do |element|
  if element % 15 == 0 
    super_array[element] <<  FizzBuzz 
  elsif element % 5 == 0
    super_array <<  Buzz 
  elsif element % 3 == 0
    super_array << "Fizz"
  else
    super_array << element
  end
end
return super_array # only return once through the whole array

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/30293542/adding-elements-to-new-array-ruby

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils