Here is my work for Exercise 13.
What is this? I’ve played around with Ruby Monk Primer and the Intro to Ruby course on Codecademy, but I have never seen arguments being entered on the command line! Pretty nifty.
1. Try giving fewer than 3 arguments to your script.
I tried first giving 2 arguments, then one argument. The output shows that the variables are not assigned. I wanted to see if this meant the variables are nil.
I added line 7 to check whether the third variable is nil.
2. Write a script that has fewer arguments and one that has more. Make sure you give the unpacked variables good names.
Here is a script with two arguments:
Since the puts method adds a new line character to the end of the line you want to print, the second variable will be printed below the first variable.
Here is my script with five arguments:
3. Combine gets.chomp with ARGV to make a script that gets more input from a user.
If you simply try to put gets.chomp in the code with your ARGV, you’ll get an error.
How come the gets method worked before when we didn’t have arguments, but now gives an error? By looking at the documentation, I saw that the gets method is using Kernel#gets. It first sees if there are any files in ARGV. If no files are present on the command line, it will take standard input($stdin). The problem is, our ARGV has 3 superhero arguments. The gets method on line 4 sees Batman, assumes that it is a file, and returns an error because the file cannot be found.
How do we get Ruby to take standard input then? We put $stdin in front of the gets method. $stdin.gets will work. Note that $stdin is identical to STDIN by default.
No more error, and our superheroes and their super powers are proudly printed.