Ruby哈希键参考 [英] Ruby Hash Key Reference

查看:85
本文介绍了Ruby哈希键参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我有一个自定义哈希,需要在API中返回.但是目前,我正在努力寻找一种很好的方法来做到这一点.下面的示例将描述问题.

Hello I have a custom Hash that needs to be returned in an API. But currently I'm struggling to find a good way to do so. The following example will describe the problem.

让我们说以下代码:

data = {name: "Jon", value: "13"}
results = []

[1, 2, 3, 4, 5].each do |i|
  data[:id] = i
  results << data
end

# output 
# results = [{name: "Jon", value: "13", id: 5}, {name: "Jon", value: "13", id: 5}, {name: "Jon", value: "13", id: 5}, {name: "Jon", value: "13", id: 5}, {name: "Jon", value: "13", id: 5}]

我期望这样的事情:

# results = [{name: "Jon", value: "13", id: 1}, {name: "Jon", value: "13", id: 2}, {name: "Jon", value: "13", id: 3}, {name: "Jon", value: "13", id: 4}, {name: "Jon", value: "13", id: 5}]

如何有效地实现这种格式(内存使用)? 以下代码解决了参考问题(因为它创建了一个新的哈希),但是效率很低,因为我的初始哈希数据"确实很大.

How can I achieve this format efficiently (memory usage)? The following code fixes the reference issue (because it creates a new hash) but is inefficient, because my initial hash 'data' is really big.

# inefficient but working
[1, 2, 3, 4, 5].each do |i|
  data[:id] = i
  results << data.dup
end

# output
# results = [{name: "Jon", value: "13", id: 1}, {name: "Jon", value: "13", id: 2}, {name: "Jon", value: "13", id: 3}, {name: "Jon", value: "13", id: 4}, {name: "Jon", value: "13", id: 5}]

谢谢!

推荐答案

您不能.

Ruby(以及几乎所有其他编程语言)中的引用都指向内存中的单个对象.

References in Ruby (and in almost every other programming language) point to a single object in memory.

irb(main):004:0> h = { foo: :bar }
=> {:foo=>:bar}
irb(main):005:0> h.object_id
=> 70125571572420

只要我突变h,我仍在使用相同的引用:

As long as I mutate h I'm still working with same reference:

irb(main):006:0> h[:bar] = 'baz'
=> "baz"
irb(main):007:0> h.object_id
=> 70125571572420

如果我想要一个稍有不同的h版本而不更改h,则它将被存储为单独的对象:

If I want a slightly different version of h without changing h it will be stored as a separate object of course:

h.merge(x: 2).object_id
=> 70125567041320

在这种情况下,

.merge复制哈希并返回将其与args合并的结果.

.merge in this case duplicates the hash and returns the result of merging it with args.

无法解决此问题. Ruby中的哈希不能从引用继承".

There is no way around this. Hashes in Ruby cannot "inherit" from a reference.

这篇关于Ruby哈希键参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆