代码之家  ›  专栏  ›  技术社区  ›  dennismonsewicz

使用gsub和数组的Ruby/Rails

  •  7
  • dennismonsewicz  · 技术社区  · 14 年前

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

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

    谢谢你的帮助!

    2 回复  |  直到 14 年前
        1
  •  13
  •   Sam å±±    14 年前
    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
    
        2
  •  17
  •   nonopolarity    14 年前

    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"] 
    
    推荐文章