首页 文章

Ruby / Rails使用gsub和数组

提问于
浏览
6

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

例如,如果我有以下原始字符串(这是我正在使用的一些示例文本,并希望将其全部工作)并且有一系列我想要搜索和替换的项目 .

我在这里先向您的帮助表示感谢!

2 回答

  • 13
    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
    
  • 15

    这是你想要的?

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

相关问题