arrays - Ruby - variable is incremented in one place, but shows as default in another -
i declare $a, , later, in loop, increment , pass widget, however, when @ output widget generating, $a perpetually 1. how can math stored in array work loop-incremented $a?
please excuse newbie code smell- also, dumbed-down version of building, attempt @ solving project euler #128
$a = 1 $arr = array.new $step1 = [1, $a-1, -1] $step2 = [$a+6, -5, 2] def widget(t,u,v) t.each |math| $arr.push (v+math)/u end end (1..100).each |num| if num % 2 == 0 $a += 1 end if [something] widget($step1,$a,num) elsif [something else] widget($step2,$a,num) end
the use of global variable makes pretty difficult read code, noted $step1
, $step2
evaluated before $a
increment, value constant, computed $a == 1:
$step1 = [1, 0, -1] # [1, (1)-1, -1] $step2 = [7, -5, 2] # [(1)+6, -5, 2]
if not desired behaviour, should move these 2 statements before if [something]
or transform step1 , step2 global variables functions.
Comments
Post a Comment