Creating a dynamic selection list with TTY-Prompt

When writing a CLI application there are some Ruby gems out there that make a big difference. TTY-prompt is without a doubt one of the most popular CLI gems out there - and for good reason. TTY-prompt is extremely helpful for reducing user error which makes your code harder to break since the user is no longer typing directly into the command line to make a selection. And, I think, improves the user experience which is important even in a small-scale application like this.

Image for post
Image for post
CLI Ruby gem TTY-prompt in action

Basically, the TTY-prompt gem works by reformatting the output to let the user scroll through a list of options and make a selection. Here is a classic example of the TTY-prompt in action:

Image for post
Image for post
Classic TTY-prompt example w/ hard-coded menu options

However, if your app is like mine you’ll need these lists to be dynamic. If your seed data changes, or if the selection list is determined by user input, you’ll code that’s more flexible than the examples given to you in the TTY-prompt documentation, that looks a lot like the main-menu example above.

Creating a dynamic list with TTY-prompt:

Image for post
Image for post
Dynamically coded TTY-prompt example

My partner and I managed it by splitting it up into three methods:

Written by

Full-Stack Software Engineer, Designer, and salsa dancer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store