1

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?

2 Answers 2

2

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_index and update the actual strings in the array:

e.g.

leuchtturmgesamtheit.each_with_index do |replace, index|
  if replace.count("1234567890") == 8
    leuchtturmgesamtheit[index] = replace[0...-1]
  end
end

another is to use map! to update the array e.g.

leuchtturmgesamtheit.map! do |entry|
  if entry.count("1234567890") == 8
    entry[0...-1]
  else
    entry
  end
end

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thx a lot for that quick and precise answer =)
Or you could use map! in the same way to replace in-place and save a few characters (the leuchtturmgesamtheit = )
1

You can use each if you use a method which alters the strings in-place (in stead of producing an altered copy):

words = %w[ACH-92941100 ACH-92941102]
words.each{|word| word.chop! if word.count('1234567890') == 8 }
p words  #=> ["ACH-9294110", "ACH-9294110"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.