开发者

In Ruby, can I make a reference to an array offset?

  1. 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]?

  2. 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 s开发者_运维知识库tored, integers being objects, like everything else in Ruby.

  3. 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜