如何在 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章