DEV Community

loading...
Cover image for 49 Days of Ruby: Day 30 - CLI: Collecting Input

49 Days of Ruby: Day 30 - CLI: Collecting Input

Ben Greenberg
Rabbi turned Coder. Second Career Dev taking it one function at a time.
・1 min read

Welcome to day 30 of the 49 Days of Ruby! 🎉

Yesterday, we began a look at building command line interfaces in Ruby. We built a small CLI that outputted some text when you ran it.

Today, we are going to collect user input in our CLI!

The examples from both yesterday and today are relatively small and concise, but they shed light on two fundamental jobs of a CLI: Sharing information and taking in information. Yesterday, we did the former, and today we'll do the latter.

How do you accept input in a CLI?

#! /usr/bin/env ruby

puts "This is my CLI!"

puts ARGV
Enter fullscreen mode Exit fullscreen mode

Now run this CLI script as such: ./cli.rb hi back at you

What is returned?

$ This is my CLI
$ ['hi', 'back', 'at', 'you']
Enter fullscreen mode Exit fullscreen mode

Did you notice that the string we added when we executed our CLI was turned into an array with each separate string as an item in the array?

That is what the ARGV keyword does.

As such, we can access specific parts of the user input like any other array:

puts ARGV[1]
Enter fullscreen mode Exit fullscreen mode
$ back
Enter fullscreen mode Exit fullscreen mode
puts ARGV[2]
Enter fullscreen mode Exit fullscreen mode
$ at
Enter fullscreen mode Exit fullscreen mode

Now you know one way to collect user input in a CLI and how to create a CLI! Tomorrow, we'll continue our Ruby adventure.

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Discussion (0)