Robert Klemme
5/28/2006 8:35:00 PM
dkmd_nielsen@hotmail.com wrote:
> I'm new to Ruby (love it!). Below is a method that works just fine.
> Passed to it as (i) is a two element array [parm,arg]. The method does
> a table lookup on @itBlock (an array of two element arrays), and
> replace the tables arg value with the arg value passed (if parm is
> found in table). I understand the variable referencing that is going
> on.
>
> def loadparm(i)
> @itBlock.each_index {|k|
> j = @itBlock[k] # for each row
> next if j[0] != i[0] # if not correct parm
> j[1] = i[1].strip! # replace argument
> k = j
> break # get out of loop
> }
> end
>
>
> What I don't understand is why the following does not work. I would
> think the variable referencing would still be in tact. The values parm
> and arg match the @itBlock row values entering and exiting the loop.
> However, the @itBlock row is not updated.
>
> def loadparm(i)
> @itBlock.each {|parm,arg|
> next if parm != i[0] # if not correct parm
> arg = i[1].strip! # replace argument
> break # get out of loop
> }
> end
>
>
> Would some explain explain what is happening to the pointers and
> variable referencing in the second example? I second question would
> be...can I accept i as two arguments, as in "def loadparm(x,y)?
You assign arg which is a block parameter. This has no effect on the
underlying collection (@itBlock). The var is simply overwritten on next
iteration. If @itBlock is a Hash you can use simple lookup, if it's an
Array you can use map!. Note also that usually variable names use
under_scores instead of camelCase. Assuming a Hash your method
basically does this
def loadparam(key, val)
@it_block[key] = val.strip!
end
Kind regards
robert