Question

Suppose I have two hashes of settings. the 'defaults' hash is initialized on startup and 'settings' hash is persisted in database. Not all settings have default, and not all settings are persisted e.g. on first startup, meaning these hashes could have different keys. I need to produce third hash 'all_settings', which will have all keys of those two, with settings key value overriding the default one if both are present:

all_settings[key] = settings[key] || defaults[key]

I've managed to do it with

all_settings = {}
defaults.each{|name, value| all_settings[name] = settings[name] || defaults[name]}
settings.each{|name, value| all_settings[name] = settings[name] || defaults[name]}

But I feel it's kind of dumb. Is there way to do the same thing using shorter and more conscise syntax?

Était-ce utile?

La solution

The method you're looking for is merge:

all_settings = defaults.merge(settings)

... will return a new hash containing all of the key-value pairs from defaults, and all of the key-value pairs from settings. If any key is duplicated, it will use the value from settings.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top