Is there better way to replace these case statement?

On Dec 22, 2013, at 3:41 PM, Joel P. [email protected] wrote:

I can’t believe I missed this obvious option
Hash.new ‘’
or
Hash.new { |hash, key| hash[key]=’’ }

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 = code_book[cmd.to_sym] || ‘’

could be written as

tool_name = 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)

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

Hope this helps,

Mike

Mike S. [email protected]
http://www.stok.ca/~mike/

The “`Stok’ disclaimers” apply.

On Sun, Dec 22, 2013 at 6:29 PM, Mike S. [email protected] wrote:

tool_name = code_book[cmd.to_sym] || ‘’
tool_name = code_book[cmd.to_sym] || ‘’
It’s another option to consider, and Avdi G.'s Confident Ruby e-book
has some good use cases for Hash#fetch (I like Avdi’s books).

+++ for Avdi’s books and for RubyTapas, where I saw Hash#fetch used
quite
elegantly.

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