It's one of those nonobvious consequences of dealing with objects.
Suppose, for the sake of argument, that you have an array of strings, thus:
@wossname = ["fee", "fie", "foe", "foo"]
Now suppose that you want to create a temporary string, which is the concatenation of the first n elements of the array, where n varies but starts at 2, and further that you need to stick a separator character, such as an underscore, between substrings, e.g., "fee_fie_foe".
Right, let's get to work!
idstring = @wossname[0] # Get base name
1.upto(n-1) do |i|
idstring << '_' + @wossname[i]
end
Which gives the expected result for idstring, but... Oopsie! @wossname[0] now holds the concatenated value, 'cause idstring is @wossname[0], not a clone thereof.
And so it cometh to pass that I now initialize idstring to '', start the loop at 0, and check for idstring!='' before inserting the separator.
(And, no, this isn't the same as Array#join, as I don't want to use all the elements every time. Though I suppose I could use @wossname[0..n-1].join('_'). Which would be kind of cryptic, and besides, I'm actually doing other things, inside the loop, with intermediate levels of idstring and some other stuff.)
Update: this other side of this, which had me really tearing my hair out, is this: being as how I'm using idstring inside the loop, and (sometimes) passing its successive values to a constructor, causing them to be incorporated into objects... I need to pass idstring.clone, or all the objects will end up with the same idstring, which will have its final value. This looks remarkably like the effect of a stale pointer.
Recent Comments