【问题标题】:Ruby/Rails working with gsub and arraysRuby/Rails 使用 gsub 和数组
【发布时间】:2010-11-01 02:38:02
【问题描述】:

我有一个字符串,我正在尝试在 Ruby 中使用 gsub 方法。问题是我有一个动态的字符串数组,我需要遍历它来搜索原始文本并替换为。

例如,如果我有以下原始字符串(这是我正在使用的一些示例文本,希望它能够正常工作)并且有一个我想要搜索和替换的项目数组。

提前感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails ruby gsub


    【解决方案1】:

    这是你要找的吗?

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

    【讨论】:

      【解决方案2】:
      a = ['This is some sample text',
           'This is some sample text',
           'This is some sample text']
      

      所以a是示例数组,然后循环遍历数组并替换值

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

      【讨论】:

        【解决方案3】:

        全部替换

        使用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]
        

        只替换匹配的元素

        使用Array#mapternary 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"]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-03
          • 2010-12-31
          • 2012-04-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多