이상한 오프바이원 게시물 업데이트 오류

레일즈(Rails) 스크립트에서 게시물 일괄 업데이트를 시도하고 있습니다. 이전 게시물 값으로 한 게시물이 업데이트되는 것처럼 보이는 이상한 오프바이원(off-by-one) 동작이 발생하고 있습니다.

내부 루프 안의 게시물(이전에는 토픽 게시물에서 값을 가져오던)에 대한 이 문제를 해결하기 위해, 이 게시물들의 업데이트를 모두 post.raw.gsub()를 직접 호출하도록 변경했습니다. 하지만 이제 토픽 N의 토픽 게시물이 토픽 N-1의 이전 마지막 게시물의 raw 값으로 업데이트되고 있습니다.

첫 번째(즉, 토픽) 게시물이 이전 반복(iteration)의 post.raw.gsub!(preg,"#{$2}") 값으로 tpost.raw.gsub!를 통해 업데이트되고 있어 더욱 혼란스럽습니다.

수정(EDIT): 마지막 버전에서 무엇이 잘못되었는지 끝내 파악하지 못했지만, 여기에는 리비전(revision)을 생성하는 게시물 일부 업데이트 스크립트 버전이 있습니다:

def fix_slack_posts
  opts = { bypass_rate_limiter: true, bypass_bump: true, skip_validations: true }
  reg=/(\*\*)(This topic was automatically generated from Slack. You can find the original thread \[here\].+?\))(\*\*\.)?\s*?([a-zA-Z, ()]* : )(.*)/m
  preg = /([a-zA-Z, ()]+? : )(.*)/m
  topic_posts = Post.where("raw like '**This topic was automatically%'")
  #topic_posts = Post.where(topic_id: [23934, 23935], post_number: 1)
  topic_posts.each do |tpost|
    begin
      puts "Fixing topic post #{tpost.id} with #{tpost.raw[0..30]}"
      puts tpost.raw.gsub(reg,"1 #{$1}\n2 #{$2}\n3 #{$3}\n4 #{$4}\n 5 #{$5}")
      raw = tpost.raw.gsub(reg,"#{$5}\n\n#{$2}.")
      puts "Fixing topic post #{tpost.id} with #{tpost.raw[0..30]}\n--->#{raw}"
      user = User.find(tpost.user_id)
      if raw.length > 10
        tpost.revise(user,{raw: raw,edit_reason: 'fix slack link location'}, opts)
      end
    rescue
      puts "Can't update topic post #{tpost.raw}"
    end
    posts = Post.where(topic_id: tpost.topic_id).where("post_number > 1")
    posts.each do |post|
      if post.raw.gsub(preg,"#{$2}").length>=10
        begin
          puts "Fixing post #{post.id} with #{post.raw[0..30]}"
          raw = post.raw.gsub(preg,"#{$2}")
          user = User.find(post.user_id)
          post.revise(user,{raw: raw,edit_reason: 'remove user name from text'}, opts)
        rescue
          puts "#{post.id}--cannot save #{post.raw}. "
        end
      end
    end
  end
end