Ruby: FizzBuzz not working as expected -
Ruby: FizzBuzz not working as expected -
i'm having problem getting if statement produce results think should. i'm not sure why cannot && ("and") conditional work.
def fizzbuzz(n) pool = [] (1..n).each |x| if x % 3 == 0 pool.push('fizz') elsif x % 5 == 0 pool.push('buzz') elsif x % 3 == 0 && x % 5 == 0 pool.push('fizzbuzz') else pool.push(x) end end puts pool end fizzbuzz(10)
and results
1 2 fizz 4 buzz fizz 7 8 fizz buzz
i'm not sure i'm doing wrong here.
try instead:
def fizzbuzz(n) pool = [] (1..n).each |x| if x % 3 == 0 && x % 5 == 0 pool.push('fizzbuzz') elsif x % 5 == 0 pool.push('buzz') elsif x % 3 == 0 pool.push('fizz') else pool.push(x) end end puts pool end
when utilize if/elsif/elsif/else, execute 1 of conditions @ time. if x % 3 == 0, that's it, ruby no longer come in of conditions, that's why fizzbuzz never printed.
ruby
Comments
Post a Comment