### Install TTY::Prompt Gem Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Instructions for installing the TTY::Prompt gem using Bundler or directly via the gem command. This is the first step to using the library in a Ruby project. ```ruby gem "tty-prompt" # Or install directly # $ gem install tty-prompt ``` -------------------------------- ### Ask a basic question in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates how to ask a simple text-based question to the user using the `ask` method. This is the most fundamental way to get user input. ```ruby prompt.ask("What is your name?") ``` -------------------------------- ### Initialize TTY::Prompt Instance Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Demonstrates how to create an instance of TTY::Prompt, with examples of basic initialization and advanced configuration. Advanced options include setting prefixes, colors, interrupt handling, input history, and custom symbols. ```ruby require "tty-prompt" # Basic initialization prompt = TTY::Prompt.new # Advanced initialization with custom options prompt = TTY::Prompt.new( prefix: "[?] ", # Prefix for all questions active_color: :cyan, # Color for selected items help_color: :bright_black, # Color for help text error_color: :red, # Color for error messages interrupt: :exit, # Handle Ctrl+C (:signal, :exit, :noop) track_history: true, # Enable input history enable_color: true, # Enable/disable colors quiet: false, # Suppress re-echoing of answers symbols: { marker: ">" } # Custom symbols ) ``` -------------------------------- ### Custom Input Conversion with Proc in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows how to use a Proc for custom input conversion in tty-prompt. This example splits a comma-separated string into an array of strings. ```ruby prompt.ask("Ingredients? (comma sep list)") do |q| q.convert -> (input) { input.split(/,\s*/) } end # Ingredients? (comma sep list) milk, eggs, flour # => ["milk", "eggs", "flour"] ``` -------------------------------- ### Configure Help Message in Select Menu Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md This code demonstrates how to add a help message to a select prompt and control when it's displayed using the `:help` and `:show_help` options. The help can appear on `start`, `never`, or `always`. ```ruby choices = %w(Scorpion Kano Jax) prompt.select("Choose your destiny?", choices, help: "(Bash keyboard keys)", show_help: :always) ``` -------------------------------- ### Configure Help Message for Multi-Select Prompt (Ruby) Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates how to configure a custom help message for a multi-select prompt using the `:help` option and control its display with `:show_help` (options: 'start', 'never', 'always'). ```ruby choices = {vodka: 1, beer: 2, wine: 3, whisky: 4, bourbon: 5} prompt.multi_select("Select drinks?", choices, help: "Press beer can against keyboard", show_help: :always) # => # Select drinks? (Press beer can against keyboard)" # ‣ ⬡ vodka # ⬡ beer # ⬡ wine # ⬡ whisky # ⬡ bourbon ``` -------------------------------- ### Configure Help Message for TTY::Prompt Slider Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows how to add and control the display of a help message for the slider using the `:help` and `:show_help` options. The help message can be shown on start, never, or always. ```ruby prompt.slider("Volume", max: 10, default: 7, help: "(Move arrows left and right to set value)", show_help: :always) # => # Volume ───────────────●────── 7 # (Move arrows left and right to set value) ``` -------------------------------- ### Use Enum Delimiter for Ordered Choices Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md This example shows how to use the `enum` option to create an ordered list of choices in a select menu. Users can then select items using arrow keys or number keys (0-9). ```ruby prompt.select("Choose your destiny?") do |menu| menu.enum "." menu.choice "Scorpion", 1 menu.choice "Kano", 2 menu.choice "Jax", 3 end ``` -------------------------------- ### Single Keypress Prompt in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows how to use `keypress` in tty-prompt to get a single character input from the user. The `:keys` option can be used to limit the accepted key presses. ```ruby prompt.keypress("Press key ?") # Press key? # => a prompt.keypress("Press space or enter to continue", keys: [:space, :return]) ``` -------------------------------- ### Convert input to float type in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows how to use the `:float` conversion type to convert user input into a floating-point number. For example, '-1' will be converted to '-1.0'. ```ruby prompt.ask("Enter a decimal number:", convert: :float) ``` -------------------------------- ### Set Default Selection in Select Menu Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md This code shows how to pre-select an item in a select menu using the `default` method. The default can be specified by index (starting from 1) or by the choice's name. ```ruby prompt.select("Choose your destiny?") do |menu| menu.default 3 # or menu.default "Jax" menu.choice "Scorpion", 1 menu.choice "Kano", 2 menu.choice "Jax", 3 end ``` -------------------------------- ### TTY::Prompt: Password/Secret Input (mask) Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Demonstrates the `mask` method for securely prompting users for sensitive information like passwords. Input characters are masked, and options for custom mask characters and disabling echo are provided. Includes an example of validation for strong passwords. ```ruby require "tty-prompt" prompt = TTY::Prompt.new # Basic password prompt (masked with dots) password = prompt.mask("Enter your password:") # => Enter your password: •••••••• # => "secretpw" # Custom mask character heart = prompt.decorate(prompt.symbols[:heart] + " ", :magenta) secret = prompt.mask("What is your secret?", mask: heart) # => What is your secret? ❤ ❤ ❤ ❤ # Hide all input (no echo) password = prompt.mask("Enter password:", echo: false) # => Enter password: # => "secretpw" # With validation for strong passwords password = prompt.mask("Create password:") do |q| q.validate(/\A(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}\Z/, "Password must be 8+ chars with uppercase, lowercase, and number") end ``` -------------------------------- ### Initialize TTY::Prompt and Ask a Question Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates how to initialize the TTY::Prompt interface and use the `ask` method to prompt the user for input. It shows how to provide a default value, which can be dynamically set using environment variables. ```ruby require "tty-prompt" prompt = TTY::Prompt.new name = prompt.ask("What is your name?", default: ENV["USER"]) # => What is your name? (piotr) ``` -------------------------------- ### Convert input to symbol type in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates the `:sym` or `:symbol` conversion type, which converts string input into a Ruby symbol. For example, 'foo' becomes `:foo`. ```ruby prompt.ask("Enter a key:", convert: :symbol) ``` -------------------------------- ### Configure Select Menu Pagination with :per_page Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates how to control the number of items displayed per page in a select menu using the `:per_page` option. This is useful for managing long lists of choices. ```ruby letters = ("A".."Z").to_a prompt.select("Choose your letter?", letters, per_page: 4) ``` ```ruby letters = ("A".."Z").to_a prompt.select("Choose your letter?") do |menu| menu.per_page 4 menu.help "(Wiggle thy finger up/down and left/right to see more)" menu.choices letters end ``` -------------------------------- ### Create Multi-Select Menus Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates the basic usage of the `multi_select` method for allowing users to select multiple options from a list. It shows how to return choice names or custom values. ```ruby choices = %w(vodka beer wine whisky bourbon) prompt.multi_select("Select drinks?", choices) ``` ```ruby choices = {vodka: 1, beer: 2, wine: 3, whisky: 4, bourbon: 5} prompt.multi_select("Select drinks?", choices) ``` ```ruby prompt.multi_select("Select drinks?") do |menu| menu.choice :vodka, {score: 1} menu.choice :beer, 2 menu.choice :wine, 3 menu.choices whisky: 4, bourbon: 5 end ``` -------------------------------- ### TTY::Prompt: Confirmation Prompts (yes?/no?) Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Explains how to use `yes?` and `no?` methods for boolean confirmation prompts. Shows basic usage with default true/false values, custom suffixes, positive/negative labels, and how to integrate with conditional logic. ```ruby require "tty-prompt" prompt = TTY::Prompt.new # Basic yes/no question (default: yes) if prompt.yes?("Do you like Ruby?") puts "Great choice!" end # => Do you like Ruby? (Y/n) # Negative question (default: no) if prompt.no?("Do you want to skip this step?") puts "Skipping..." end # => Do you want to skip this step? (y/N) # Custom suffix and labels answer = prompt.yes?("Are you human?") do |q| q.suffix "Yup/Nope" q.positive "Yup" q.negative "Nope" end # => Are you human? (Yup/Nope) ``` -------------------------------- ### Set Default Value for TTY::Prompt Slider Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Illustrates setting a default starting value for the slider, either numerically or by name. This pre-selects a value when the prompt is first displayed. ```ruby prompt.slider("Volume", max: 100, step: 5, default: 75) # => # Volume ───────────────●────── 75 # (Use ←/→ arrow keys, press Enter to select) ``` ```ruby prompt.slider("Letter", ('a'..'z').to_a, default: 'q') # => # Letter ──────────────────●─────── q # (Use ←/→ arrow keys, press Enter to select) ``` -------------------------------- ### TTY::Prompt: Simple Text Input (ask) Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Shows how to use the `ask` method for basic text input. Covers features like default values, pre-populated values for editing, type conversion (e.g., to integer), regex validation, required input, range validation, and using a block DSL for complex configurations. ```ruby require "tty-prompt" prompt = TTY::Prompt.new # Basic question name = prompt.ask("What is your name?") # => What is your name? John # => "John" # With default value name = prompt.ask("What is your name?", default: ENV["USER"]) # => What is your name? (piotr) # => "piotr" # With pre-populated value for editing name = prompt.ask("What is your name?", value: "John") # => What is your name? John # With type conversion age = prompt.ask("How old are you?", convert: :int) # => How old are you? 30 # => 30 # With validation using regex email = prompt.ask("What is your email?", validate: /\A\w+@\w+\.\w+\Z/) # => What is your email? invalid # => >> Your answer is invalid (must match (?-mix:\A\w+@\w+\.\w+\Z)) # => What is your email? user@example.com # => "user@example.com" # With required input phone = prompt.ask("What's your phone number?", required: true) # => What's your phone number? # => >> Value must be provided # With range validation rating = prompt.ask("Rate 1-10:", convert: :int, in: "1-10") # => Rate 1-10: 15 # => >> Value 15 must be within the range 1..10 # Using block DSL for advanced configuration username = prompt.ask("Enter username:") do |q| q.required true q.validate(/\A[a-z0-9_]+\Z/i, "Username can only contain letters, numbers, and underscores") q.modify :downcase, :strip q.convert :symbol end # => :john_doe ``` -------------------------------- ### Create Select Menu with Choices Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md This demonstrates creating a select menu using the `prompt.select` method with an array of strings as choices. The default return value is the choice name itself. ```ruby prompt.select("Choose your destiny?", %w(Scorpion Kano Jax)) ``` ```ruby prompt.select("Choose your destiny?") do |menu| menu.choice "Scorpion" menu.choice "Kano" menu.choice "Jax" end ``` ```ruby prompt.select("Choose your destiny?") do |menu| menu.choice "Scorpion", 1 menu.choice "Kano", 2 menu.choice "Jax", -> { "Nice choice captain!" } end ``` ```ruby choices = {"Scorpion" => 1, "Kano" => 2, "Jax" => 3} prompt.select("Choose your destiny?", choices) ``` -------------------------------- ### Convert input to a list of integers in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows the `:ints` or `:int_list` conversion type, which parses comma-separated input into an array of integers. For example, '1,2,3' becomes `[1, 2, 3]`. ```ruby prompt.ask("Enter numbers separated by commas:", convert: :ints) ``` -------------------------------- ### Convert input to a list of floats in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Illustrates the `:floats` or `:float_list` conversion type for parsing comma-separated input into an array of floating-point numbers. For example, '1.1,2.2,3.3' becomes `[1.1, 2.2, 3.3]`. ```ruby prompt.ask("Enter decimal numbers separated by commas:", convert: :floats) ``` -------------------------------- ### Expand Menu for Key-Based Selection Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Shows how to create an expand menu where single-key shortcuts expand to reveal full options. This is useful for confirmations or quick selections. It supports basic choices, DSL with Procs, and auto-hint. ```ruby require "tty-prompt" prompt = TTY::Prompt.new # Basic expand menu choices = [ { key: "y", name: "overwrite this file", value: :yes }, { key: "n", name: "do not overwrite this file", value: :no }, { key: "a", name: "overwrite all files", value: :all }, { key: "d", name: "show diff", value: :diff }, { key: "q", name: "quit", value: :quit } ] answer = prompt.expand("Overwrite Gemfile?", choices) # Using block DSL with Proc values answer = prompt.expand("Overwrite Gemfile?") do |q| q.choice key: "y", name: "Overwrite" do :ok end q.choice key: "n", name: "Skip", value: :no q.choice key: "a", name: "Overwrite all", value: :all q.choice key: "d", name: "Show diff", value: :diff q.choice key: "q", name: "Quit", value: :quit end # With auto-hint enabled answer = prompt.expand("Overwrite?", choices, auto_hint: true) ``` -------------------------------- ### Range Validation with 'in' Option in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates using the `in` option in tty-prompt to validate that user input falls within a specified range of values. This example ensures a digit between 0 and 9 is provided. ```ruby prompt.ask("Provide number in range: 0-9?") { |q| q.in("0-9") } ``` -------------------------------- ### Create Menu Selection Choices in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates methods for defining choices in a menu prompt. Choices can be provided as a simple array of strings, where the string is both the displayed name and the returned value. Alternatively, a hash can be used to map custom display names to specific values. ```ruby choices = %w(small medium large) ``` ```ruby choices = {small: 1, medium: 2, large: 3} prompt.select("What size?", choices) # => # What size? (Press ↑/↓ arrow to move and Enter to select) # ‣ small # medium ``` -------------------------------- ### Configure Pagination for Multi-Select Prompt (Ruby) Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows how to customize the number of items displayed per page in a multi-select prompt using the `:per_page` option. The default is 6 items. ```ruby letters = ("A".."Z").to_a prompt.multi_select("Choose your letter?", letters, per_page: 4) # => # Which letter? (Use ↑/↓ and ←/→ arrow keys, press Space to select and Enter to finish) # ‣ ⬡ A # ⬡ B # ⬡ C # ⬡ D ``` -------------------------------- ### Configure Cycling Navigation in Multi-Select with :cycle Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Explains the `:cycle` option for `multi_select`, which allows the selection cursor to wrap around the list when navigating to the top or bottom. ```ruby prompt.multi_select("Select drinks?", %w(vodka beer wine), cycle: true) ``` -------------------------------- ### Confirm Input with TTY::Prompt's yes?/no? Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows how to use the `yes?` method from TTY::Prompt to ask a boolean confirmation question. This is useful for simple yes/no interactions with the user. ```ruby require "tty-prompt" prompt = TTY::Prompt.new prompt.yes?("Do you like Ruby?") ``` -------------------------------- ### Multi-Selection Menu Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Displays an interactive menu for selecting multiple options. Users can toggle selections with the Space key and confirm with Enter. Supports default selections, minimum/maximum limits, enumeration, and filtering. ```ruby require "tty-prompt" prompt = TTY::Prompt.new # Basic multi-selection drinks = prompt.multi_select("Select drinks:", %w(vodka beer wine whisky bourbon)) # => Select drinks? (Use ↑/↓ arrow keys, press Space to select and Enter to finish) # => ⬡ vodka # => ‣ ⬢ beer # ⬡ wine # ⬢ whisky # ⬡ bourbon # => ["beer", "whisky"] # With hash values choices = { vodka: 1, beer: 2, wine: 3, whisky: 4, bourbon: 5 } selected = prompt.multi_select("Select drinks:", choices) # => [2, 4] # With default selections (by index or name) drinks = prompt.multi_select("Select drinks:") do |menu| menu.default 2, 5 # or menu.default :beer, :bourbon menu.choice :vodka, { score: 10 } menu.choice :beer, { score: 20 } menu.choice :wine, { score: 30 } menu.choice :whisky, { score: 40 } menu.choice :bourbon, { score: 50 } end # => [{ score: 20 }, { score: 50 }] # With minimum/maximum selections drinks = prompt.multi_select("Select 2-4 drinks:", %w(vodka beer wine whisky bourbon), min: 2, max: 4) # => Select 2-4 drinks? (min. 2, max. 4) ... # With enumeration drinks = prompt.multi_select("Select drinks:") do |menu| menu.enum ")" menu.choice :vodka, 1 menu.choice :beer, 2 menu.choice :wine, 3 end # => ⬡ 1) vodka # => ⬢ 2) beer # => ‣ ⬡ 3) wine # With filtering choices = %w(vodka beer wine whisky bourbon) drinks = prompt.multi_select("Select drinks:", choices, filter: true) # Press 'w' to filter: # => Select drinks? (Filter: "w") # => ‣ ⬡ wine # ⬡ whisky # Keyboard shortcuts: # - Space: toggle current selection # - Ctrl+A: select all # - Ctrl+R: reverse selection # - Enter: confirm selection ``` -------------------------------- ### Expand Prompt with Choices Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows how to use the `expand` prompt for questions with many options. Choices must include `:key`, `:name`, and `:value`. The `:key` is a single character. Help is automatically added. ```ruby choices = [ { key: "y", name: "overwrite this file", value: :yes }, { key: "n", name: "do not overwrite this file", value: :no }, { key: "q", name: "quit; do not overwrite this file ", value: :quit } ] prompt.expand("Overwrite Gemfile?", choices) ``` -------------------------------- ### Select multiple options from a list in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows how to use the `multi_select` method to allow users to select multiple items from a list. Users can select/deselect items using the spacebar and confirm their choices by pressing Enter. ```ruby choices = %w(vodka beer wine whisky bourbon) prompt.multi_select("Select drinks?", choices) ``` -------------------------------- ### Enum Select with DSL Choices (Ruby) Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows how to define choices for `enum_select` using a DSL with the `choice` method, allowing for custom values associated with each choice name. ```ruby choices = %w(nano vim emacs) prompt.enum_select("Select an editor?") do |menu| menu.choice :nano, "/bin/nano" menu.choice :vim, "/usr/bin/vim" menu.choice :emacs, "/usr/bin/emacs" end # => # # Select an editor? # 1) nano # 2) vim # 3) emacs # Choose 1-3 [1]: # # Select an editor? /bin/nano ``` -------------------------------- ### Expandable prompt with key bindings in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates the `expand` method, which provides a prompt with predefined key bindings for various actions. This is useful for complex confirmations or choices where users can trigger actions with single key presses. ```ruby choices = [ { key: "y", name: "overwrite this file", value: :yes }, { key: "n", name: "do not overwrite this file", value: :no }, { key: "a", name: "overwrite this file and all later files", value: :all }, { key: "d", name: "show diff", value: :diff }, { key: "q", name: "quit; do not overwrite this file ", value: :quit } ] prompt.expand("Overwrite Gemfile?", choices) ``` -------------------------------- ### Configure Pagination for Enum Select Prompt (Ruby) Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows how to customize the number of items displayed per page in an enum select prompt using the `:per_page` option. The default is 6 items. ```ruby letters = ("A".."Z").to_a prompt.enum_select("Choose your letter?", letters, per_page: 4) # => ``` -------------------------------- ### Configure TTY::Prompt Slider using DSL Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Illustrates configuring a slider using a block-based DSL. This provides a more structured way to set various slider options like range, step, default, and format. ```ruby prompt.slider("What size?") do |range| range.max 100 range.step 5 range.default 75 range.format "|:slider| %d%%" end # => # Volume |───────────────●──────| 75% # (Use ←/→ arrow keys, press Enter to select) ``` ```ruby prompt.slider("What letter?") do |range| range.choices ('a'..'z').to_a range.format "|:slider| %s" range.default 'q' end # => # What letter? |──────────────────●───────| q # (Use ←/→ arrow keys, press Enter to select) ``` -------------------------------- ### Single Keypress Input with TTY-Prompt Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Captures a single keypress from the user. Can be configured to accept specific keys or include a timeout for automatic continuation. Supports displaying a countdown during the timeout. ```ruby require "tty-prompt" prompt = TTY::Prompt.new # Wait for any key key = prompt.keypress("Press any key to continue") # => Press any key to continue # => "a" # Wait for specific keys only key = prompt.keypress("Press space or enter:", keys: [:space, :return]) # With timeout (auto-continue after 3 seconds) key = prompt.keypress("Press any key (auto-resumes in 3s)...", timeout: 3) # With countdown display key = prompt.keypress("Resumes in :countdown seconds...", timeout: 5) # => Resumes in 5 seconds... # => Resumes in 4 seconds... # => ... ``` -------------------------------- ### Set Default Selections in Multi-Select Menus Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Illustrates how to pre-select choices in a multi-select menu using the `default` option, which accepts choice indices or names. ```ruby prompt.multi_select("Select drinks?") do |menu| menu.default 2, 5 # or menu.default :beer, :whisky menu.choice :vodka, {score: 10} menu.choice :beer, {score: 20} menu.choice :wine, {score: 30} menu.choice :whisky, {score: 40} menu.choice :bourbon, {score: 50} end ``` -------------------------------- ### Select a single option from a list in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates the `select` method for presenting a list of options to the user and allowing them to choose one using arrow keys. The available options are provided as an array. ```ruby prompt.select("Choose your destiny?", %w(Scorpion Kano Jax)) ``` -------------------------------- ### Enforce Minimum Selections in Multi-Select (Ruby) Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows how to enforce a minimum number of selections in a multi-select prompt using the `:min` option. The prompt will not allow the user to proceed until the minimum is met. ```ruby choices = %w(vodka beer wine whisky bourbon) prompt.multi_select("Select drinks?", choices, min: 3) # => # Select drinks? (min. 3) vodka, beer # ⬢ vodka # ⬢ beer # ⬡ wine # ⬡ wiskey # ‣ ⬡ bourbon ``` -------------------------------- ### Paginated Enum Select with Disabled Choices Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Demonstrates how to use `enum_select` with pagination and disabled choices. The `per_page` option controls how many items are shown at once. Disabled choices are indicated with a message. ```ruby editors = [ { name: "Emacs", disabled: "(not installed)" }, "Atom", "GNU nano", { name: "Notepad++", disabled: "(not installed)" }, "Sublime", "Vim" ] prompt.enum_select("Select editor:", editors, per_page: 4) ``` -------------------------------- ### Customize TTY::Prompt Slider Formatting Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Explains how to customize the slider's output format using the `:format` option. This allows for dynamic display of the selected value, including percentages and decimal places, or even custom logic via a proc/lambda. ```ruby prompt.slider("Volume", max: 100, step: 5, default: 75, format: "|:slider| %d%%मीटर") # => # Volume |───────────────●──────| 75% # (Use ←/→ arrow keys, press Enter to select) ``` ```ruby prompt.slider("Volume", max: 10, step: 0.5, default: 5, format: "|:slider| %.1f") # => # Volume |───────────────●──────| 7.5 # (Use ←/→ arrow keys, press Enter to select) ``` ```ruby slider_format = -> (slider, value) { "|#{slider}| #{value.zero? ? "muted" : "%.1f"}" % value } prompt.slider("Volume", max: 10, step: 0.5, default: 0, format: slider_format) # => # Volume |●─────────────────────| muted # (Use ←/→ arrow keys, press Enter to select) ``` -------------------------------- ### Configure Integer Slider with TTY::Prompt Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates configuring a slider for integer values with minimum, maximum, and step options. The slider visually represents the selected value using a bullet symbol. ```ruby prompt.slider("Volume", min: 0, max: 100, step: 5) # => # Volume ──────────●────────── 50 # (Use ←/→ arrow keys, press Enter to select) ``` -------------------------------- ### Basic Enum Select Prompt (Ruby) Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates the basic usage of `enum_select` for standard selection from an indexed list. It takes a question and an array of choices. ```ruby choices = %w(emacs nano vim) prompt.enum_select("Select an editor?", choices) # => # # Select an editor? # 1) nano # 2) vim # 3) emacs # Choose 1-3 [1]: ``` -------------------------------- ### Expand Prompt with DSL Choices Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Illustrates using a DSL with the `choice` method to define options for an `expand` prompt. The `:value` can be a primitive or a `Proc`. The first choice is the default. ```ruby prompt.expand("Overwrite Gemfile?") do |q| q.choice key: "y", name: "Overwrite" do :ok end q.choice key: "n", name: "Skip", value: :no q.choice key: "a", name: "Overwrite all", value: :all q.choice key: "d", name: "Show diff", value: :diff q.choice key: "q", name: "Quit", value: :quit end ``` -------------------------------- ### Indexed Selection Menu Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Displays an enumerated selection menu where users can directly select options by typing their corresponding numbers. Supports custom values and enum delimiters. ```ruby require "tty-prompt" prompt = TTY::Prompt.new # Basic enumerated selection editor = prompt.enum_select("Select an editor:", %w(nano vim emacs)) # => Select an editor? # 1) nano # 2) vim # 3) emacs # Choose 1-3 [1]: # => "vim" # With custom values and enum delimiter editor = prompt.enum_select("Select editor:") do |menu| menu.default 2 menu.enum "." menu.choice :nano, "/bin/nano" menu.choice :vim, "/usr/bin/vim" menu.choice :emacs, "/usr/bin/emacs" end # => 1. nano # 2. vim # 3. emacs # Choose 1-3 [2]: # => "/usr/bin/vim" ``` -------------------------------- ### Configure Array Slider with TTY::Prompt Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows how to configure a slider using an array of choices, suitable for non-numeric selections. The slider allows users to pick an item from the provided list. ```ruby prompt.slider("Letter", ('a'..'z').to_a) # => # Letter ────────────●───────────── m # (Use ←/→ arrow keys, press Enter to select) ``` -------------------------------- ### Enable Dynamic Filtering in Select Menus with :filter Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Explains how to enable dynamic searching within a select menu using the `:filter` option. Users can type to filter choices, and the filter can be cleared using Backspace or Canc. ```ruby warriors = %w(Scorpion Kano Jax Kitana Raiden) prompt.select("Choose your destiny?", warriors, filter: true) ``` -------------------------------- ### Single Selection Menu Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Displays an interactive menu for selecting a single option from a list. Supports pagination, filtering, cycling, and enumeration. It can accept arrays or hashes as choices and allows customization via a block DSL. ```ruby require "tty-prompt" prompt = TTY::Prompt.new # Basic selection from array size = prompt.select("What size?", %w(small medium large)) # => What size? (Use ↑/↓ arrow keys, press Enter to select) # => ‣ small # medium # large # => "medium" # With hash values size = prompt.select("What size?", { small: 1, medium: 2, large: 3 }) # => 2 # Using block DSL with custom values choice = prompt.select("Choose your destiny:") do |menu| menu.choice "Scorpion", 1 menu.choice "Kano", 2 menu.choice "Jax", -> { "Nice choice!" } # Proc value end # With default selection (by index or name) editor = prompt.select("Select editor:") do |menu| menu.default 3 # or menu.default "vim" menu.choice "nano", "/bin/nano" menu.choice "emacs", "/usr/bin/emacs" menu.choice "vim", "/usr/bin/vim" end # => Select editor? (Use ↑/↓ arrow keys, press Enter to select) # nano # emacs # ‣ vim # With enumeration (numbered list) editor = prompt.select("Select editor:") do |menu| menu.enum "." menu.choice :nano menu.choice :vim menu.choice :emacs end # => 1. nano # 2. vim # ‣ 3. emacs # Paginated menu (default: 6 items per page) letter = prompt.select("Choose letter:", ("A".."Z").to_a, per_page: 4) # => Choose letter? (Use ↑/↓ and ←/→ arrow keys, press Enter to select) # => ‣ A # B # C # D # With cycling enabled choice = prompt.select("Choose:", %w(first second third), cycle: true) # With filtering enabled warrior = prompt.select("Choose warrior:", %w(Scorpion Kano Jax Kitana Raiden), filter: true) # => Choose your destiny? (Filter: "k") # => ‣ Kano # Kitana # Disabled choices warriors = [ "Scorpion", "Kano", { name: "Goro", disabled: "(injured)" }, "Jax" ] prompt.select("Choose warrior:", warriors) # => ‣ Scorpion # Kano # ✘ Goro (injured) # Jax ``` -------------------------------- ### Collect for Structured Data Input Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Enables gathering multiple answers into a structured hash. It supports nested keys, required fields, type conversion, validation, and collecting multiple values for a single key. ```ruby require "tty-prompt" prompt = TTY::Prompt.new # Basic collection result = prompt.collect do key(:name).ask("Name?") key(:age).ask("Age?", convert: :int) end # With nested structure result = prompt.collect do key(:name).ask("Name?") key(:age).ask("Age?", convert: :int) key(:address) do key(:street).ask("Street?", required: true) key(:city).ask("City?") key(:zip).ask("Zip?", validate: /\A\d{5}\Z/) end end # Collecting multiple values for a key result = prompt.collect do key(:name).ask("Name?") while prompt.yes?("Add another address?") key(:addresses).values do key(:street).ask("Street?") key(:city).ask("City?") end end end ``` -------------------------------- ### Suggest Possible Matches Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Utilizes the `suggest` method to offer possible matches for user input from a given list. It displays a list of suggestions if the input is ambiguous. ```ruby prompt.suggest("sta", ["stage", "stash", "commit", "branch"]) ``` -------------------------------- ### Multiline Input with TTY-Prompt Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Allows users to enter multiline text input. Supports default values and custom DSL for configuration. Input is returned as an array of strings, each representing a line. ```ruby require "tty-prompt" prompt = TTY::Prompt.new # Basic multiline input description = prompt.multiline("Description?") # => Description? (Press CTRL-D or CTRL-Z to finish) # => Line 1 # => Line 2 # => Line 3 # => ["Line 1\n", "Line 2\n", "Line 3\n"] # With default value description = prompt.multiline("Description?", default: "Enter description here") # Using DSL description = prompt.multiline("Description?") do |q| q.default "A super sweet prompt." q.help "Press Ctrl+D to finish" end ``` -------------------------------- ### Keyboard Event Handling with TTY-Prompt Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Allows subscribing to and handling various keyboard events, such as keypresses, keydowns, and keyups. Provides detailed event properties like key name, value, and modifier states (meta, shift, ctrl). Supports chaining multiple event handlers. ```ruby require "tty-prompt" prompt = TTY::Prompt.new # Subscribe to keypress events prompt.on(:keypress) do |event| puts "Key: #{event.key.name}, Value: #{event.value}" end # Vim-style navigation for select menus prompt.on(:keypress) do |event| if event.value == "j" prompt.trigger(:keydown) elsif event.value == "k" prompt.trigger(:keyup) end end # Event properties: # event.key.name - key name (:up, :down, :enter, letter, etc.) # event.key.meta - true if meta key pressed # event.key.shift - true if shift pressed # event.key.ctrl - true if ctrl pressed # event.value - the character value # Available events: # :keypress, :keydown, :keyup, :keyleft, :keyright # :keynum, :keytab, :keyenter, :keyreturn, :keyspace # :keyescape, :keydelete, :keybackspace # Chain multiple event handlers prompt.on(:keypress) { |e| handle_keypress(e) } .on(:keydown) { |e| handle_down(e) } .on(:keyup) { |e| handle_up(e) } ``` -------------------------------- ### Collect Multiple Values in a Loop Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows how to collect multiple values for a key within a loop using `key(...).values`. This is useful for gathering lists of similar data, such as multiple addresses. ```ruby result = prompt.collect do key(:name).ask("Name?") key(:age).ask("Age?", convert: :int) while prompt.yes?("continue?") key(:addresses).values do key(:street).ask("Street?", required: true) key(:city).ask("City?") key(:zip).ask("Zip?", validate: /\A\d{3}\Z/) end end end ``` -------------------------------- ### Enum Select with Default and Custom Enum Format (Ruby) Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Illustrates how to set a default selected choice and customize the numbering format for `enum_select` using `default` and `enum` options within the DSL. ```ruby choices = %w(nano vim emacs) prompt.enum_select("Select an editor?") do |menu| menu.default 2 # or menu.defualt "/usr/bin/vim" menu.enum "." menu.choice :nano, "/bin/nano" menu.choice :vim, "/usr/bin/vim" menu.choice :emacs, "/usr/bin/emacs" end # => # # Select an editor? # 1. nano # 2. vim # 3. emacs # Choose 1-3 [2]: # # Select an editor? /usr/bin/vim ``` -------------------------------- ### Enable Enumerated Choices in Multi-Select with :enum Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates how to use the `:enum` option to display numbered choices in a multi-select menu, allowing selection via number keys in addition to arrow keys. ```ruby prompt.multi_select("Select drinks?") do |menu| menu.enum ")" menu.choice :vodka, {score: 10} menu.choice :beer, {score: 20} menu.choice :wine, {score: 30} menu.choice :whisky, {score: 40} menu.choice :bourbon, {score: 50} end ``` -------------------------------- ### Convert input to file path in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows the `:filepath` conversion type, which converts user input into a file path string. This is useful for ensuring consistent path formatting. ```ruby prompt.ask("Enter a file path:", convert: :filepath) ``` -------------------------------- ### Custom Confirmation Prompt Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Creates a customizable confirmation prompt that allows setting default values, suffixes, positive/negative labels, and custom input conversion logic. It returns a boolean value based on user input. ```ruby require "tty-prompt" prompt = TTY::Prompt.new agree = prompt.yes?("Accept terms?") do |q| q.default false q.suffix "Agree/Disagree" q.positive "Agree" q.negative "Disagree" q.convert -> (input) { !input.match(/^agree$/i).nil? } end # => Accept terms? (agree/Disagree) ``` -------------------------------- ### Suggestion Helper with TTY-Prompt Source: https://context7.com/piotrmurach/tty-prompt/llms.txt Assists users by suggesting possible matches for partial or misspelled input from a given list. Supports custom text for single matches and plural suggestions. ```ruby require "tty-prompt" prompt = TTY::Prompt.new # Basic suggestion prompt.suggest("sta", ["status", "stage", "stash", "commit", "branch"]) # => Did you mean one of these? # stage # stash # Single match with custom text prompt.suggest("b", %w(status stage stash commit branch blame), indent: 4, single_text: "Perhaps you meant?") # => Perhaps you meant? # blame # Custom plural text prompt.suggest("st", %w(status stage stash), plural_text: "Did you mean one of these commands?") ``` -------------------------------- ### Print Success Message with TTY::Prompt ok Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Uses the `ok` method to print a message in green, typically used for success notifications. ```ruby prompt.ok('Operation successful!') ``` -------------------------------- ### Convert input to a hash from key-value pairs in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates the `:map` or `:hash` conversion type, which parses input like 'a:1 b:2 c:3' into a hash. By default, keys are converted to symbols and values remain strings. ```ruby prompt.ask("Enter key-value pairs (e.g., a:1 b:2): ", convert: :map) ``` -------------------------------- ### Ask a complex question with validation and modification in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Shows how to use the `ask` method with a block to define more complex input requirements, including making the question mandatory (`required true`) and validating the input against a regular expression (`validate /Aw+Z/`). It also demonstrates modifying the input using `:capitalize`. ```ruby prompt.ask("What is your name?") do |q| q.required true q.validate /\A\w+\Z/ q.modify :capitalize end ``` -------------------------------- ### Pre-populating Input Line with Value in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates using the `:value` option in tty-prompt to pre-populate the input line, allowing the user to edit the existing text. ```ruby prompt.ask("What is your name?", value: "Piotr") # => # What is your name? Piotr ``` -------------------------------- ### Customize Suggestion Text Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates customizing the query text for the `suggest` method using `:single_text` and `:plural_text` options. This allows for more specific prompts when one or multiple suggestions are available. ```ruby possible = %w(status stage stash commit branch blame) prompt.suggest("b", possible, indent: 4, single_text: "Perhaps you meant?") ``` -------------------------------- ### Convert input to a hash of integers in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates the `:int_map` or `:integer_map` or `:int_hash` conversion type. It parses input like 'a:1 b:2 c:3' into a hash where keys are symbols and values are integers. ```ruby prompt.ask("Provide keys and values (e.g., a:1 b:2): ", convert: :int_map) ``` -------------------------------- ### Convert input to a hash with string keys and integer values in Ruby Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Explains the `:str_int_map` or `:string_integer_hash` conversion type. This parses input like 'a:1 b:2 c:3' into a hash with string keys and integer values. ```ruby prompt.ask("Provide key-value pairs (e.g., count1:10 count2:20): ", convert: :str_int_map) ``` -------------------------------- ### Print Colored Message with TTY::Prompt say Source: https://github.com/piotrmurach/tty-prompt/blob/master/README.md Demonstrates printing messages with specific colors using the `say` method's `:color` option. Supports colors defined by the Pastel library. ```ruby prompt.say('Message', color: :blue) ```