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"
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.
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.
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.
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 }.
Indirectly perhaps...
foo = { :world => 'World', :hello => lambda { "Hello #{foo[:world]}" }} puts foo[:hello].call
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With