Ruby/Rails working with gsub and arrays Ruby/Rails working with gsub and arrays ruby ruby

Ruby/Rails working with gsub and arrays


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"] 


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


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"]