ruby - Why does changing the order of conditionals break my code? -


i have created ping-pong test in ruby. monkey patches fixnum class new method, ping_pong, loops on range (0..self), checks conditions on each element, , constructs array of results.

the resulting array have ping numbers in range divisible 3, pong numbers divisible 5, , ping-pong numbers divisible both.

my question is, why code work if part:

elsif (num.%(3) == 0) && (num.%(5) == 0) array.push("ping-pong") 

is ahead of other elsif statements? tried putting after other elsifs didn't work.

here's code:

class fixnum   define_method(:ping_pong)     array = [0]     total = (0..self)     total = total.to_a     total.each() |num|       if (num == 0)         array.push(num)       elsif (num.%(3) == 0) && (num.%(5) == 0)         array.push("ping-pong")       elsif (num.%(3) == 0)         array.push("ping")       elsif (num.%(5) == 0)         array.push("pong")       else         array.push(num)       end     end     array   end end 

when have multiple if/elsif blocks chained together, 1 of them run, , first block have true condition 1 run. so, order of blocks matters. example:

if true   puts 'this code run' elsif true   puts 'this code not run' end 

even though conditions blocks both true, first 1 run. if want have both run, use 2 separate if blocks, this:

if true   puts 'this code run' end  if true   puts 'this code run' end 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -