Hash question

I’m using FXRuby and YAML, but this question deals with using a hash :

Is there a better/easier way to do this?

self.backColor = @options[“GUI”].has_key?(“backColor”) ?
@options[“GUI”][“backColor”] : FXColor::Red

Basically, if backColor is a key then use that key’s value else use the
default.

I’m going to have a lot of these…I wonder if there is a better way to handle
this…

···

Kurt

There is no good nor evil; there is only power.

Does this work?
self.backColor = @options[“GUI”][“backColor”] ||= FXColor::Red

warning: this is off my head, and not tried…

Kurt V. Hindenburg wrote:

···

I’m using FXRuby and YAML, but this question deals with using a hash :

Is there a better/easier way to do this?

self.backColor = @options[“GUI”].has_key?(“backColor”) ?
@options[“GUI”][“backColor”] : FXColor::Red

Basically, if backColor is a key then use that key’s value else use the
default.

I’m going to have a lot of these…I wonder if there is a better way to handle
this…


Wai-Sun “Squidster” Chia
Consulting & Integration
Linux/Unix/Web Developer Dude
“Just Another Ruby Miner”

value = hash[key] || default

The other response recommended

value = hash[key] ||= default

Be warned, that modifies the hash, which is not what you asked.

Since you have a lot of keys and defaults, a nice approach is to put
all the default values into a separate hash, then do something like
this:

final_hash = given_hash.dup.update(defaults_hash)

Cheers,
Gavin

···

On Sunday, December 29, 2002, 5:53:11 PM, Kurt wrote:

I’m using FXRuby and YAML, but this question deals with using a hash :

Basically, if backColor is a key then use that key’s value else use the
default.

Yea, it works…thanks!

···

On Sunday 29 December 2002 1:59 am, Wai-Sun Chia wrote:

self.backColor = @options[“GUI”][“backColor”] ||= FXColor::Red

Kurt

There is no good nor evil; there is only power.

Sorry, that should be:

final = defaults.dup.update(given)

See KeywordArguments on the Wiki for some somewhat related code.

Cheers,
Gavin

···

On Sunday, December 29, 2002, 8:49:19 PM, Gavin wrote:

Since you have a lot of keys and defaults, a nice approach is to put
all the default values into a separate hash, then do something like
this:

final_hash = given_hash.dup.update(defaults_hash)