I have a problem with an if condition that I want to use within a block. More precisely I want to get a string from an array, change that string and save it back to the array if a certain condition holds.
I have an array called “leuchtturmgesamtheit” which consists of strings.
Most of those strings look like this:
ACH-92941100
ACH-92941102
My aim is to aggregate those two strings. Thats why I want to rename the strings so that they have the same name. To do that I want to cut of the last character. After that I can use uniq! on the array.
Here is what I did:
leuchtturmgesamtheit.each { |replace|
if replace.count("1234567890")==8
replace=replace[0...-1]
end
}
leuchtturmgesamtheit.uniq!
print leuchtturmgesamtheit
I expected to get:
ACH-9294110
But instead I get the same two strings back.
RubyMine tells me that the bold marked “replace” is a local variable not used after assignment. So the problem seems to be the if condition inside the block. What did I do wrong?
replace=replace[0...-1]is only changing which string the local variable within the block refers to and is not updating the entries in the array. There are a couple of solutions.One is to use
each_with_indexand update the actual strings in the array:e.g.
another is to use
map!to update the array e.g.steenslag’s answer is also good for scenarios where the string manipulation needed can be done on methods that modify the existing string, as is the case here.