Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby hash - create element using an element which is being created within the hash

Tags:

ruby

hash

Self descriptive non-working code:

mr_hash = {alpha: "hello", bravo: self.alpha + " world"} # Not working...

should give

{alpha: "hello", bravo: "hello world"}

Is it possible, and if so how, to do it within the hash? Without using intermediate variables like:

charlie = "hello"
delta = charlie + " world"
mr_hash = {alpha: charlie, bravo: delta}
like image 851
xxjjnn Avatar asked May 08 '26 12:05

xxjjnn


1 Answers

Probably not what you're looking for but you can use Object#tap to avoid creating an additional variable:

mr_hash = Hash.new.tap do |h|
  h['alpha'] = 'Hello'
  h['bravo'] = h['alpha'] + ' world'
end
mr_hash # => {"alpha"=>"Hello", "bravo"=>"Hello world"} 
like image 85
maerics Avatar answered May 10 '26 09:05

maerics