Method: CommandKit::Interactive#ask_multiple_choice

Defined in:
lib/command_kit/interactive.rb

#ask_multiple_choice(prompt, choices, **kwargs) ⇒ String

Asks the user to select a choice from a list of options.

Examples:

Array of choices:

ask_multiple_choice("Select a flavor", %w[Apple Orange Lemon Lime])
#   1) Apple
#   2) Orange
#   3) Lemon
#   4) Lime
#   Select a flavor: 4
#
# => "Lime"

Hash of choices:

ask_multiple_choice("Select an option", {'A' => 'Foo',
                                         'B' => 'Bar',
                                         'X' => 'All of the above'})
#   A) Foo
#   B) Bar
#   X) All of the above
#   Select an option: X
#
# => "All of the above"

Parameters:

  • prompt (String)

    The prompt that will be printed before reading input.

  • choices (Hash{String => String}, Array<String>)

    The choices to select from.

  • kwargs (Hash{Symbol => Object})

    Additional keyword arguments for #ask.

Options Hash (**kwargs):

  • default (String, nil)

    The default option to fallback to, if no input is given.

  • required (Boolean)

    Requires non-empty input.

Returns:

  • (String)

    The selected choice.



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/command_kit/interactive.rb', line 185

def ask_multiple_choice(prompt,choices,**kwargs)
  choices = case choices
            when Array
              Hash[choices.each_with_index.map { |value,i|
                [(i+1).to_s, value]
              }]
            when Hash
              choices
            else
              raise(TypeError,"unsupported choices class #{choices.class}: #{choices.inspect}")
            end

  prompt = "#{prompt} (#{choices.keys.join(', ')})"

  loop do
    # print the choices
    choices.each do |choice,value|
      stdout.puts "  #{choice}) #{value}"
    end
    stdout.puts

    # read the choice
    choice = ask(prompt,**kwargs)

    if choices.has_key?(choice)
      # if a valid choice is given, return the value
      return choices[choice]
    else
      stderr.puts "Invalid selection: #{choice}"
    end
  end
end