Ruby splat operator changing value inside loop -
I want to define a method that can take an optional amount of arguments and hashes, like
def foo (* b, ** c) 2.times.map.with_index {| I | New_hash, new_array = {}, bc.map {| Key, value | New_hash [key] = Value [i] Do not assume [i] .nil? } New_array & lt; & Lt; New_hash if new_hash.length & gt; 0 send (: bar, new_array)} Enddef bar (* b) PB &
If I have understood the split and double split operators correctly (which I doubt), then Send this array to b
to the bar
method, and by adding only new_hash
to foo
if there is something in it Something strange - I try with a few snippets below and give an example
# invoking #foo foo (a, key: 'value') #foo #foo # i First repeat 0 # B [] # C {: key = & gt; ['Value1']} # transmissions (: bar, new_array) = & gt; Send (: bar, [[:: key => 'value1'}]) # Bar yield: [{: :: key = & gt; 'Value1'}]
Now, something happens
# duplicates #foo # i in # duplication is # 1B [: key = & Gt; 'Value1'] & lt; ---- Why? # Is c {: key = & gt; ['Value1']
Why has the value of b
changed inside the loop of foo
?
edit code has been updated to display a new array for each error
new_hash, new_array = {}, b
it has not created a copy of b
. Now point to new_array
and b
point the same object and modifying one place, the other will be modified.
new_array & lt; & Lt; New_hash
modifies that code to new_array
(and thus b
), so the new element remains on the next move. Do some experiment like +
, which creates a copy:
Send (: bar, * (B + (new_hash.mp)? []: [New_hash] )))
Comments
Post a Comment