Hafiz Temuri
Hafiz Temuri

Reputation: 4122

How to assign a pointer to a variable in Ruby

I am new to Ruby, just wondering if its possible to assign a reference to a hash-key to a variable?

a = {
  foo: 1
}
b = a[:foo] // I don't want assign the value
b = 2
puts a

Instead of assigning the value, is there a way to assign a reference? It just that I don't want to keep writing a[:foo], instead anytime b changes, I want to reflect it on a[:foo]. Perhaps a macro that simply replaces the text, wherever I write ACCESS_FOO it will replace with a[:foo].

I apologize if this is asked before. Anytime I search for pointers C language pops up.

Upvotes: 1

Views: 474

Answers (2)

Christopher Oezbek
Christopher Oezbek

Reputation: 26363

In Ruby every variable is just a pointer/reference to an instance, there isn't anything else.

a = { foo: "Hello" }
b = a[:foo]
b.gsub!('e', 'a')
puts a.inspect
# => { foo: "Hallo" }

So in your example b is not assigned a copy of "Hello", it really is a reference to the same instance stored in the hash.

When you assign to a variable though, you are replacing the reference/pointer stored in the variable with something else.

What you seem to try to do is go one level deeper: You want to have a pointer to a reference (kind of a P** in C, I guess). In Ruby you can solve this with any kind of additional object which can store your value. How about an array?

a = { foo: [1] }
b = a[:foo]
b[0] = 2
puts a.inspect
# => { foo: [2] }

Upvotes: 2

Fernand
Fernand

Reputation: 1333

You can't.

There are no pointers in Ruby, the variable only hold a reference.
https://robertheaton.com/2014/07/22/is-ruby-pass-by-reference-or-pass-by-value/

But you can implement your own method. probably using eval()

Upvotes: 1

Related Questions