Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

331
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda