cmd = "gca_shell"
case cmd # there is a special relationship between case and #===
when astro; puts "doing astro stuff"
when gcas; puts "doing gcas stuff"
end
···
On 12/20/2013 02:57 AM, Previn Lin wrote:
Is there better way to replace these case statement?
Thank you so much for your warm help, with your guide, I can use hash
method to replace case statement succesfully.
Yes, as Jason noticed, for this case, reg. needed, and not every reg has
'$' in the end. Also thanks Eric's solution, I know the first time how
to use reg in the hash.
I still not fully understand Joel VanderWerf's method, I'll go on study
it, would you give more help if needed?
Thank you so much for your warm help, with your guide, I can use hash
method to replace case statement succesfully.
Yes, as Jason noticed, for this case, reg. needed, and not every reg has
'$' in the end. Also thanks Eric's solution, I know the first time how
to use reg in the hash.
I still not fully understand Joel VanderWerf's method, I'll go on study
it, would you give more help if needed?
Thanks Joel. Just noticed not every reg has '$' in the end. The following code should work the same as the 'case/when':
#the last one is the default
code_book=[ [/^Astro$/, 'Astro'], [/^core/, 'coretools'], [/^(fm_shell|formality)$/, 'fm'], [/^gca_shell$/, 'gcas'], [/^xa/, 'xa'], [/.*/, '']]
cmd=gets.chomp
p code_book.collect { |reg, tool_name| tool_name if cmd =~ reg}.compact.shift
Downside is it will not break after find the first match, bright side is you can catch if multiple matches exist.
J.T
···
-----Original Message-----
From: ruby-talk on behalf of Joel Pearson
Sent: Sat 12/21/2013 8:58 AM
To: ruby-talk@ruby-lang.org
Subject: Re: RE: Is there better way to replace these case statement?
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.
-----Original Message-----
From: ruby-talk on behalf of Jason Tao
Sent: Sat 12/21/2013 1:20 PM
To: ruby-talk@ruby-lang.org; ruby-talk@ruby-lang.org
Subject: RE: RE: Is there better way to replace these case statement?
Thanks Joel. Just noticed not every reg has '$' in the end. The following code should work the same as the 'case/when':
#the last one is the default
code_book=[ [/^Astro$/, 'Astro'], [/^core/, 'coretools'], [/^(fm_shell|formality)$/, 'fm'], [/^gca_shell$/, 'gcas'], [/^xa/, 'xa'], [/.*/, '']]
cmd=gets.chomp
p code_book.collect { |reg, tool_name| tool_name if cmd =~ reg}.compact.shift
Downside is it will not break after find the first match, bright side is you can catch if multiple matches exist.
J.T
-----Original Message-----
From: ruby-talk on behalf of Joel Pearson
Sent: Sat 12/21/2013 8:58 AM
To: ruby-talk@ruby-lang.org
Subject: Re: RE: Is there better way to replace these case statement?
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.