【问题标题】:Why are these two variables ending up equal?为什么这两个变量最终相等?
【发布时间】:2019-03-17 10:35:50
【问题描述】:

我正在尝试用单词和句子制作一个二维数组,然后制作另一个与之匹配但翻译成英文的二维数组。

这是我创建新课程时发生的课程模型的回调:

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_contentlesson.html_content 最终彼此相等?

我原以为lesson.parsed_content 是中文,lesson.html_content 是英文,但他们最终都是英文。我可能太累了,但我不明白为什么lesson.parsed_content 也以英文结尾。

【问题讨论】:

    标签: ruby


    【解决方案1】:

    你在他们两个中引用了同一个数组:

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

    只做lesson.parsed_content = text 不会复制text,它只是复制引用,所以你最终会得到四个指向同一条数据的东西:

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

    每个赋值只是将另一个指针添加到同一个底层数组。

    你不能用一个简单的lesson.parsed_content = text.dup 来解决这个问题,因为dup 只做一个浅拷贝并且不会复制内部数组。既然您知道您有一个数组数组,您可以手动 dup 外部和内部数组来获取完整副本,或者您可以使用标准的深度复制方法之一,例如往返于 Marshal .或者完全跳过复制,遍历textarray,但修改一个单独的数组。

    【讨论】:

    • 谢谢。那行得通。我真的每天都在学习新东西。
    猜你喜欢
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 2019-10-22
    • 1970-01-01
    • 2021-12-11
    相关资源
    最近更新 更多