Reputation: 325
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
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
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