Hello - last question for the next time
How can I create a data-structure (only), including a reference to a value
of itself?
x[1,x[0]] is dissolved (x[1] contains the value 1 now.
x[1] should be a ptr to x[0]
Berg
Hello - last question for the next time
How can I create a data-structure (only), including a reference to a value
of itself?
x[1,x[0]] is dissolved (x[1] contains the value 1 now.
x[1] should be a ptr to x[0]
Berg
Ruby doesn't have pointers. It does store objects by reference, and you
*can* have the same object stored multiple times in a container, but unless
you can mutate the object itself there's no way to distinguish this from
just making a copy.
a = "hello"
=> "hello"
b = [a, "world"]
=> ["hello", "world"]
b.push(b[0])
=> ["hello", "world", "hello"]
a.upcase!
=> "HELLO"
b
=> ["HELLO", "world", "HELLO"]
but
a = 1
=> 1
b = [a, 2]
=> [1, 2]
b.push(b[0])
=> [1, 2, 1]
# now what?
ignoring the fact that integers specifically are stored in an immediate
form, even if they were both references to the same object "1" there is no
way to mutate the number.
If you want an *assignment* to b[0] to change b[2], that is not going to
happen just due to the fact that the ruby model is for a variable to be an
alias for an object, not a pointer to it, and the array class follows that
model. e.g. if you say
a = "hello"
=> "hello"
b = a
=> "hello"
c = b
=> "hello"
a.upcase!
=> "HELLO"
[a, b, c]
=> ["HELLO", "HELLO", "HELLO"]
but
b = a
=> "hello"
c = b
=> "hello"
c = c.upcase
=> "HELLO"
[a, b, c]
=> ["hello", "hello", "HELLO"]
because the assignment operator makes the variable "c" an alias for a *new*
object; the link to a is not retained.
Note that array slots are not really variables, they just mimic the
behaviour. So you could define your own collection class that wrapped an
array and overloaded the = operator to keep track of when two slots had
to mirror each other; the built-in Array class simply doesn't do that.
martin
On Sat, Apr 23, 2016 at 6:36 AM, A Berger <aberger7890@gmail.com> wrote:
Hello - last question for the next time
How can I create a data-structure (only), including a reference to a value
of itself?x[1,x[0]] is dissolved (x[1] contains the value 1 now.
x[1] should be a ptr to x[0]Berg
Unsubscribe: <mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
How can I create a data-structure (only), including a reference to a value of itself?
x[1,x[0]] is dissolved (x[1] contains the value 1 now.
x[1] should be a ptr to x[0]
No, if you want it self-referential, it should be a pointer to x:
x = [1]; x << x
=> [1, [...]]
On Apr 23, 2016, at 06:36, A Berger <aberger7890@gmail.com> wrote:
Ok, thanks all+especiallyMartin!
Berg
Ok, thanks all+especiallyMartin+Ryan!
Berg