On Dec 22, 2013, at 3:41 PM, Joel Pearson <lists / ruby-forum.com> wrote:

> Joel Pearson wrote in post #1131366:
>> Jason Tao wrote in post #1131307:
>>> tool_name =3D code_book[cmd.to_sym]
>>>=20
>>> The downside I see here is it returns nil instead of "" if there is =
no
>>> matching.
>>=20
>> There's this option:
>>=20
>> tool_name =3D code_book[cmd.to_sym] || ''
>=20
> I can't believe I missed this obvious option
> Hash.new ''
> or
> Hash.new { |hash, key| hash[key]=3D'' }

You might want to consider Hash#fetch which gives you the flexibility to =
supply a default at when accessing keys, rather than making it a basic =
property of the Hash. For example:

  tool_name =3D code_book[cmd.to_sym] || ''

could be written as=20

  tool_name =3D code_book.fetch(cmd.to_sym, '')

In that case you don't see much benefit; Hash#fetch has other tricks up =
its sleeve, like allowing a block to be called when a missing key's =
value is fetched, and raising an exception if no default is supplied (so =
you don't have to figure out where that nil came from later=85)

It's another option to consider, and Avdi Grimm's Confident Ruby e-book =
has some good use cases for Hash#fetch (I like Avdi's books).

Hope this helps,

Mike

--=20

Mike Stok <mike / stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.