0

単語と文から2D配列を作成し、それに一致するが英語に翻訳された別の2D配列を作成しようとしています。

新しいレッスンを作成するときに発生するレッスンモデルからのコールバックは次のとおりです。

before_create do |lesson|
  require 'rmmseg'
  require "to_lang"
  require "bing_translator"

  lesson.parsed_content =[]
  lesson.html_content = []
  RMMSeg::Dictionary.load_dictionaries

  text = lesson.content
  text = text.gsub("。","^^.")
  text = text.gsub("?","~~?")
  text = text.gsub("!", "||!")

  text = text.split(/[.?!]/u) #convert to an array
  text.each do |s|
    s.gsub!("^^","。")
    s.gsub!("~~","?")
    s.gsub!("||","!")
  end

  text.each_with_index do |val, index|
    algor = RMMSeg::Algorithm.new(text[index])
    splittext = []
    loop do
      tok = algor.next_token
      break if tok.nil?
      tex = tok.text.force_encoding('UTF-8')
      splittext << tex
      text[index] = splittext
    end
  end

  lesson.parsed_content = text
  textarray = text
  translator = BingTranslator.new(BING_CLIENT_ID, BING_API_KEY)
  ToLang.start(GOOGLE_TRANSLATE_API)
  textarray.each_with_index do |sentence, si| #iterate array of sentence
    textarray[si] = []
    sentence.each_with_index do |word,wi| #iterate sentence's array of words
      entry = DictionaryEntry.find_by_simplified(word) #returns a DictionaryEntry object hash
      if entry == nil #for cases where there is no DictionaryEntry
        textarray[si] << word
      else
        textarray[si] << entry.definition
      end
    end
    lesson.html_content = textarray
  end
end

なぜ私の変数lesson.parsed_contentとはlesson.html_content互いに等しくなるのですか?

lesson.parsed_content中国語と英語を期待していましlesson.html_contentたが、どちらも英語になってしまいました。疲れすぎかもしれませんが、なぜlesson.parsed_content英語になってしまうのかわかりません。

4

1 に答える 1

4

両方で同じ配列を参照しています。

lesson.parsed_content = text
textarray = text
# Various in-place modifications of textarray...
lesson.html_content = textarray

実行するだけでlesson.parsed_content = textは重複しませんtext。参照をコピーするだけなので、同じデータを指す 4 つのものになります。

text ------------------=-+--+--+----> [ ... ]
lesson.parsed_content -=-/  |  |
lesson.html_content ---=----/  |
textarray -------------=-------/

各割り当ては、同じ基になる配列に別のポインターを追加するだけです。

浅いコピーのみを行い、内部配列を複製しないlesson.parsed_content = text.dupため、この問題を単純に修正することはできません。dup配列の配列があることがわかっているので、外側と内側の配列を手動で完全なコピーを取得するか、 Marshaldupを介したラウンド トリップなどの標準的なディープ コピー アプローチのいずれかを使用できます。または、コピーを完全にスキップし、反復して別の配列を変更します。textarray

于 2012-12-27T05:14:46.387 に答える