如何在 Ruby 中複製哈希? - How do I copy a hash in Ruby?

問題:

I'll admit that I'm a bit of a ruby newbie (writing rake scripts, now).我承認我有點像 ruby​​ 新手(現在正在編寫 rake 腳本)。 In most languages, copy constructors are easy to find.在大多數語言中,很容易找到複製構造函數。 Half an hour of searching didn't find it in ruby.找了半個小時沒在ruby裏找到。 I want to create a copy of the hash so that I can modify it without affecting the original instance.我想創建一個散列的副本,這樣我就可以在不影響原始實例的情況下修改它。

Some expected methods that don't work as intended:一些無法按預期工作的預期方法:

h0 = {  "John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
h1=Hash.new(h0)
h2=h1.to_hash

In the meantime, I've resorted to this inelegant workaround與此同時,我採用了這種不雅的解決方法

def copyhash(inputhash)
  h = Hash.new
  inputhash.each do |pair|
    h.store(pair[0], pair[1])
  end
  return h
end

解決方案:

參考一: https://en.stackoom.com/question/HRWp
參考二: https://stackoom.com/question/HRWp
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章