Frage

I'm trying to be really efficient with # of lines of code so I want to combine the following two lines of code:

my_hash["X"] = value
my_hash

If I take out the second line, then my function returns the wrong thing because it will only return the one element of the hash. Is there any way to add the element to the hash that will return the whole hash? Thanks in advance!

War es hilfreich?

Lösung

Do as below using merge! :

my_hash.merge!("X" => value)

Andere Tipps

tap will yield the object to a block, and then return it:

my_hash.tap { |h| h['X'] = value }

Be aware that reducing lines of code for the sake of reducing lines of code only reduces readability and clarity of purpose, it rarely improves code quality.

my_hash.merge!( { 'X' => value } )
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top