Get first entries of case / when menus

Hi.

Is there a simple way to get all first entries of a case/when menu?

like when you have:

case x
when ‘abc’,‘def’
do_this
when ‘ghi’,‘h’
do_that
end

I’d need an array of ‘abc’ and ‘ghi’

The reason I need this is based on additions for Readline completion.

So that users can autocomplete all case/when menu options that exist,
but only as first entries of said case menu.

On Sun, Dec 8, 2013 at 7:49 AM, Marc H. [email protected]
wrote:

Hi.

Is there a simple way to get all first entries of a case/when menu?

like when you have:

case x
when ‘abc’,‘def’

  (first_case ||= []) << x

when ‘abc’,‘def’
The reason I need this is based on additions for Readline completion.

So that users can autocomplete all case/when menu options that exist,
but only as first entries of said case menu.

http://www.ruby-doc.org/stdlib-2.0.0/libdoc/abbrev/rdoc/Abbrev.html

Are you looking for something like what the Abbrev class in Ruby’s
Standard library does?

Marc H. wrote:

do_that
end

I’d need an array of ‘abc’ and ‘ghi’

You can’t do it directly on the case statement but you can store the
options elsewhere and use splat for the case syntax:

OPTIONS = [['abc', 'def'], ['ghi', 'h']]

case x
when *OPTIONS[0]
  first_option = OPTIONS.detect { |a| a.include?(x) }[0]
  do_this
when *OPTIONS[1]
  do_that
end

Andrew V.

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