-2

I tired to use map to solve fizzbuzz.

def fizzbuzz(n)
    array =(1..n).to_a
    array.map{|x| 
        if x % 3 == 0 && x % 5 == 0
         x = 'FizzBuzz'
        elsif x % 3 == 0 
         x = 'Fizz'
        elsif x % 5 == 0
         x = 'Buzz'
        end
    } 
   array
end

Somehow, it doesn't work. Do you know what's wrong?

sawa
  • 165,429
  • 45
  • 277
  • 381
Han Jiang
  • 41
  • 3
  • 10

2 Answers2

4

Method map does not change the original array. Use the bang version map! instead.

Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35
yzalavin
  • 1,788
  • 1
  • 13
  • 19
1

Using map! as suggested by @tmc and some other changes try:

def fizzbuzz(n)
    array =(1..n).to_a

    array.map!{|x| 
        if x % 3 == 0 && x % 5 == 0
         x = 'FizzBuzz'
        elsif x % 3 == 0 
         x = 'Fizz'
        elsif x % 5 == 0
         x = 'Buzz'
        else
         x = x
        end
    }

   p array
end

fizzbuzz(10) #=> [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz"]

As you can see I've added a call to the method fizzbuzz with an argument of 10 which you can change. And I've used p to inspect the array as well as a final else statement.

Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35
  • You can rid of `x = ` and just have rest of expression - given that last executed statement is the return value. Also, if you use just `array.map`, then, you don't need `p array`. You don't need `array` variable itself - as you can do `(1..n).map` – Wand Maker Jan 29 '16 at 09:04
  • @WandMaker I agree with you about your recommendations (although I'll leave it for the OP to sort out) except I can't see how the array gets returned or printed without `p` or similar? – Sagar Pandya Jan 29 '16 at 12:43
  • 1
    No worries. Array should be ideally printed by printing the result of `fizzbuzz(...)` method call. – Wand Maker Jan 29 '16 at 13:15