-
-
Save ElaineYu/6096120 to your computer and use it in GitHub Desktop.
def super_fizzbuzz(array) | |
#Create new hash | |
hash = Hash.new(0) | |
array.each_index do |value| | |
hash[value] = array[value] | |
if hash[value] % 3 == 0 && hash[value] % 5 == 0 | |
hash[value] = "Fizzbuzz" | |
elsif hash[value] % 3 == 0 #&& hash[value] % 5 != 0 | |
hash[value] = "Fizz" | |
elsif hash[value] % 5 == 0 #&& hash[value] % 3 != 0 | |
hash[value] = "Buzz" | |
end | |
end | |
new_array = [] | |
hash.each do |key, value| | |
new_array.push(value) | |
end | |
new_array | |
end | |
#Better solution | |
def super_fizzbuzz(array) | |
array.map! { |element| | |
if(element % 3 == 0 && element % 5 == 0) | |
"FizzBuzz" | |
elsif(element % 3 == 0) | |
"Fizz" | |
elsif (element % 5 == 0) | |
"Buzz" | |
else | |
element | |
end | |
} | |
return array | |
end |
I would work with the bottom template, as that's closer to what I had.
That said, I don't think the [i-1] parts are necessary...neither are the "&& i % _ != 0"
Try setting a new empty array at the beginning that you can concatenate into through your nesting statement and then return the new array at the end.
hm, I don't think the syntax for your first super_fizzbuzz method is correct. When you iterate over an array with the each method, you can't call the index of an element. for example, for this setup:
array.each do |x|
[methods]
end
the variable (in this case x) returns the value of each element, not the index. so array[x] wouldn't return x, but some other variable at location x within the array -- which is not particularly valuable.
to access the index values of an array, you can instead use the #each_with_index method. you can also use a hash, since hash.each allows you to play with both the index key and value of each element.
Hi Elaine, the way you have it set up, you might want to take a look at this .
Your have the right approach, but Ruby has built in methods that make this process much easier, in this case Array#each is not returning your resulting array because it wasn't designed to return anything but itself. That is not to say you can't use Array#each to accomplish this but you won't be able to change the original array using Array#each as you are trying to do here. Make sure you check out the docs. Hope that helps!
testing...hmm...