Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Self reference in hash

Tags:

Is it possible to reference one element in a hash within another element in the same hash?

# Pseudo code foo = { :world => "World", :hello => "Hello #{foo[:world]}" } foo[:hello] # => "Hello World" 
like image 225
polarblau Avatar asked Mar 22 '11 20:03

polarblau


People also ask

How do you reference a hash in Ruby?

In Ruby, a hash is a collection of key-value pairs. A hash is denoted by a set of curly braces ( {} ) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket ( => ). Calling the hash followed by a key name within brackets grabs the value associated with that key.

Is hash ordered in Ruby?

Hashes are inherently unordered. Hashes provide amortized O(1) insertion and retrieval of elements by key, and that's it. If you need an ordered set of pairs, use an array of arrays.

What is Ruby hashes?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.

How to define a hash in rails?

Just like arrays, hashes can be created with hash literals. Hash literals use the curly braces instead of square brackets and the key value pairs are joined by =>. For example, a hash with a single key/value pair of Bob/84 would look like this: { "Bob" => 84 }.


2 Answers

Indirectly perhaps...

foo = { :world => 'World', :hello => lambda { "Hello #{foo[:world]}" }}  puts foo[:hello].call 
like image 96
DigitalRoss Avatar answered Nov 10 '22 11:11

DigitalRoss


If you want to make values of some keys dependent on others:

foo = Hash.new{|h, k|    case k    when :hello; "Hello #{h[:world]}"    when :bye; "Bye #{h[:world]}"    end } foo[:world] = 'World' foo[:hello] # => 'Hello World' foo[:bye] # => 'Bye World' foo[:world] = 'Heaven' foo[:hello] # => 'Hello Heaven' foo[:bye] # => 'Bye Heaven' 
like image 21
sawa Avatar answered Nov 10 '22 13:11

sawa