开发者

Ruby/Rails working with gsub and arrays

开发者 https://www.devze.com 2023-01-23 02:08 出处:网络
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

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 fo开发者_开发问答llowing 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!


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

精彩评论

暂无评论...
验证码 换一张
取 消