0

How can I do this in Ruby?
For example, in Ruby:

a = [1,2,3]
h= {vara: a} 
p h[:vara] # [1,2,3]

a = [42,43,44]
p h[:vara] # [1,2,3] - still the same

Hash shows the same results (array [1,2,3]) although I have changed a.
As for this example, I want hash shows different results when a changes:

a = [1,2,3]
h= {vara: a} 
p h[:vara] # [1,2,3]

a = [42,43,44]
p h[:vara] # [42,43,44] - changed!

How to do it in general case - variable nor container (hash in above example) isn't specified?

For example, in the C++ you can use reference:

#include <iostream>
#include <stdlib>
int main(void)
{
   int a = 10;
   int &var = a;
   std::cout<< "\na = "<< a <<"\n";
   a = 42;
   std::cout<< "\nnew var = " << var << "\n"; //
   std::cout<< "\nnew a = " << a << "\n";

   system("pause");
   return 0;
}

will produce:

a = 10

new var = 42

new a = 42

Is there something like this in the Ruby?

Darek Nędza
  • 1,420
  • 1
  • 12
  • 19

2 Answers2

4

You simply replace the containment of the instance of the Array with the #replace method, because the = assignment operator just assing to a variable name an other instance:

a = [1,2,3]
h = {vara: a} 
h[:vara]
# => [1,2,3]

a.replace [42,43,44]
h[:vara]
# => [42, 43, 44]
Малъ Скрылевъ
  • 16,187
  • 5
  • 56
  • 69
3

Ruby has references, but they're more like C++ pointers (with transparent dereferencing).

There's no equivalent of C/C++ references. You can always write a C extension, though.

Instead of completely replacing "a" reference itself, you can replace the content of what it points to.

a = [1,2,3]
h= {vara: a} 
p h[:vara] 

a.replace([40, 41, 42]) # <== note here
p h[:vara] 
# >> [1, 2, 3]
# >> [40, 41, 42]

In this case, both h[:para] and a are still pointing to the same array. But when you assign to a, the link breaks.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • The problem with `replace` is that it is not in every class. As I have checked only `String`, `Array`, `Hash` contain this method. +1 because it works for some part of ruby classes. ps. SO says that you were faster (few minutes). – Darek Nędza Jan 29 '14 at 10:56
  • I was the first, yes. But @Малъ posted code with replace a few seconds before I updated my answer. :) – Sergio Tulentsev Jan 29 '14 at 11:22
  • @DarekNędza: anyway, apart from getting to low-level (C ext), I don't know what can be done here. – Sergio Tulentsev Jan 29 '14 at 11:23