在 Ruby 中,我可以引用数组偏移量吗?
在 Ruby 中,我可以做一些类似 C 的事情吗,就像这样(使用我虚构的运算符“&”):
a = [1,2,3,4] 且 b = &a[2], b => [3,4],如果我设置 b[0] = 99,则 a => [1,2,-9,4]?
如果数组的元素是整数,Ruby 是否需要将它们连续存储在一个数组中 内存的连续部分?我猜“不”,只存储地址,整数 对象,就像 Ruby 中的其他所有内容一样。
如果第二个问题的答案是“是”(我对此表示怀疑),是否有一种方法可以有效地移动块 内存,例如在 C 中可以做到的。
In Ruby, can I do something C-like, like this (with my made-up operator '&'):
a = [1,2,3,4] and b = &a[2], b => [3,4], and if I set b[0] = 99, a => [1,2,-9,4]?
If the elements of an array are integers, does Ruby necessary store them consecutively in a
contiguous part of memory? I'm guessing "no", that only addresses are stored, integers being
objects, like everything else in Ruby.If the answer to #2 is "yes" (which I doubt), is there a way to efficiently shift blocks of
memory, as one can do in C, for example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Ruby 中没有内置这样的功能(Ruby 数组不是由 cons 单元构建的,并且获取地址的级别比 Ruby 操作的级别要低得多),不过说实话,编写这样的东西并不难。
回答第二个问题:它不一定是连续的整数数组。 MRI 将整数视为立即值(最低有效位作为标志,指示一个字代表整数还是对象地址),因此它可能会以这种方式存储它。其他实现按照自己的方式进行。
There is no such functionality built into Ruby (Ruby arrays are not built of cons cells, and taking the address is much lower level than Ruby operates), though honestly it would not be hard to write something like that.
To answer the second question: It wouldn't necessarily be a contiguous array of integers. MRI treats integers as immediate values (with the least significant bit as a flag indicating whether a word represents an integer or an object address), so it would probably store it that way. Other implementations do it their own way.