Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

337
Views
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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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()

over 4 years ago · Santiago Trujillo Report

0

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] }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!