kotyara85
kotyara85

Reputation: 325

Reference inside hash

I have a hash:

test = {
  :key1 => "Test",
  :key2 => "Test2",
  :key3 => REF TO KEY1
}

Is it possible to let key3 refer to the key1 value?

Upvotes: 0

Views: 71

Answers (2)

bunji
bunji

Reputation: 5213

This is really not recommended and my guess is that there is a better way to solve whatever larger problem you are attempting to solve with this technique.

But one way you could do this is by creating a Hash whose default_proc returns the value of :key1 if it is passed :key3.

> test = Hash.new { |h,k| k == :key3 ? h[:key1] : nil }
> test[:key1] = "Test"
> puts test[:key3]
Test

And this acts as a reference as can be seen if we modify the value of :key1

> test[:key1] = "Test2"
> puts test[:key3]
Test2  

Upvotes: 1

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

Yes, this is easily possible. The expression for the value can be any arbitrary Ruby expression, including of course accessing a value from a Hash:

test = {
  :key1 => "Test",
  :key2 => "Test2",
}

test[:key3] = test[:key1]

Upvotes: 1

Related Questions