8

I have a string that I am trying to work with in using the gsub method in Ruby. The problem is that I have a dynamic array of strings that I need to iterate through to search the original text for and replace with.

For example if I have the following original string (This is some sample text that I am working with and will hopefully get it all working) and have an array of items I want to search through and replace.

Thanks for the help in advance!

3 Answers 3

21

Is this what you are looking for?

ruby-1.9.2-p0 > arr = ["This is some sample text", "text file"]  
 => ["This is some sample text", "text file"] 

ruby-1.9.2-p0 > arr = arr.map {|s| s.gsub(/text/, 'document')}
 => ["This is some sample document", "document file"] 
Sign up to request clarification or add additional context in comments.

Comments

14
a = ['This is some sample text',
     'This is some sample text',
     'This is some sample text']

so a is the example array, and then loop through the array and replace the value

a.each do |s|
    s.gsub!('This is some sample text', 'replacement')
end

Comments

0

Replace everything

Using Array#fill.

irb(main):008:0> a
=> {:a=>1, :b=>2, :c=>3, :d=>nil, :e=>5}
irb(main):009:0> a.values
=> [1, 2, 3, nil, 5]
irb(main):010:0> a.values.fill(:x)
=> [:x, :x, :x, :x, :x]

Replace only matching elements

Using Array#map and a ternary operator.

irb(main):008:0> a
=> {:a=>1, :b=>2, :c=>3, :d=>nil, :e=>5}
irb(main):009:0> a.values
=> [1, 2, 3, nil, 5]
irb(main):012:0> a.values.map { |x| x.nil? ? 'void' : x }
=> [1, 2, 3, "void", 5]
irb(main):016:0> a.values.map { |x| /\d/.match?(x.to_s) ? 'digit' : x }
=> ["digit", "digit", "digit", nil, "digit"]

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.