Is there better way to replace these case statement?

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 Grimm's Confident Ruby e-book has some good use cases for Hash#fetch (I like Avdi's books).

Hope this helps,

Mike

···

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

The downside I see here is it returns nil instead of "" if there is no
matching.

There's this option:

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

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

--

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

The "`Stok' disclaimers" apply.

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

···

On Sun, Dec 22, 2013 at 6:29 PM, Mike Stok <mike@stok.ca> wrote:

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 = code_book[cmd.to_sym]
>>>
>>> The downside I see here is it returns nil instead of "" if there is no
>>> matching.
>>
>> There's this option:
>>
>> tool_name = code_book[cmd.to_sym] || ''
>
> 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 Grimm's Confident Ruby e-book
has some good use cases for Hash#fetch (I like Avdi's books).