0

I want to replace string in CSV::Table. I could replace the string by using gsub! like this:

csv = CSV.table(@csv_file)
csv[:tag].each do |tag|
  tag.gsub!('Replace1','Replace2')
  tag.gsub!('Replace3','Replace4')
end

But I prefer to use gsub with method chain

csv[:tag].each do |tag|
  tag = tag.gsub('Replace1','Replace2').
            gsub('Replace3','Replace4')
end

Unfortunately it doesn't change the csv[:tag] strings. How can I replace string in CSV::Table class without using gsub!?

1 Answer 1

1

gsub! returns self, so you can do the same thing:

tag.gsub!('Replace1','Replace2').
    gsub!('Replace3','Replace4')

If you want to replace a string with a string you already calculated, you can use String#replace:

new_tag = tag.gsub('Replace1','Replace2').
              gsub('Replace3','Replace4')
tag.replace(new_tag)
Sign up to request clarification or add additional context in comments.

2 Comments

probably the assignment is unneccesary
gsub! return self only when there is match, so I'll use replace method. Thanks!

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.