Assignment if key_exist? in Hash

Hi all,

I have a bunch of lines like:

foo = some_hash[“some_key”] if some_hash.has_key?(“some_key”)

This feels awkward and cumbersome, so I would imagine there is a more
idiomatic way to write it.

Thanks,
-d

From: darren kirby [mailto:[email protected]]

> foo = some_hash[“some_key”] if some_hash.has_key?(“some_key”)

try,

foo = some_hash[“some_key”] || foo

kind regards -botp

On Mar 31, 2008, at 9:30 PM, Peña, Botp wrote:

foo = some_hash[“some_key”] || foo

that replaces even if the key is set to ‘false’, ‘nil’, or if the has
does not have the key… but prolly what OP wants…

regards.

a @ http://codeforpeople.com/

quoth the Peña, Botp:

From: darren kirby [mailto:[email protected]]

> foo = some_hash[“some_key”] if some_hash.has_key?(“some_key”)

try,

foo = some_hash[“some_key”] || foo

kind regards -botp

That’s the one.
Thanks botp,

-d

quoth the ara.t.howard:

On Mar 31, 2008, at 9:30 PM, Peña, Botp wrote:

foo = some_hash[“some_key”] || foo

that replaces even if the key is set to ‘false’, ‘nil’, or if the hash
does not have the key…

I don’t understand…If the hash key doesn’t exist then foo retains its
original value. That is the behaviour I require:

foo = “Some String”
h = {}
foo = h[“none_such”] || foo
=> “Some String”
h = {“some_key”=>“some value”}
foo = h[“some_key”] || foo
=> “some value”

-d

What he’s saying is if you want to retain the value of “false” or
“nil”, that won’t work too well

Learn about Ruby on Rails! CHECK OUT THE FREE VIDS (LIMITED TIME) NEW
VIDEO OUT 3rd MARCH
http://sensei.zenunit.com/

quoth the Julian L.:

What he’s saying is if you want to retain the value of “false” or
“nil”, that won’t work too well

Ahh, OK.

Not a prob. In my use case the hash key will be set to a string or it
will not
exist.

Thanks all,
-d

darren kirby wrote:

quoth the Julian L.:

What he’s saying is if you want to retain the value of “false” or
“nil”, that won’t work too well

Ahh, OK.

Not a prob. In my use case the hash key will be set to a string or it will not
exist.

You could also use
foo = hash.fetch(“some_key”, foo)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs