简体   繁体   English

使用 gsub 和数组的 Ruby/Rails

[英]Ruby/Rails working with gsub and arrays

I have a string that I am trying to work with in using the gsub method in Ruby.我有一个字符串,我试图在 Ruby 中使用 gsub 方法来处理它。 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!提前感谢您的帮助!

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 是示例数组,然后遍历数组并替换值

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

Replace everything更换一切

Using Array#fill .使用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 .使用Array#map三元运算符

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM