Friday, November 11, 2011

Exercise 14: Prompting And Passing: Learn Ruby The Hard Way: Practicum

So as I mentioned yesterday, I wasn't sure how to get gets.chomp() and ARGV to play together. When in doubt, check ahead and you might find an answer. Well, that's what I did and I found out something cool.

This example shows ways to isolate and focus on individual variables, as well as how to get gets.chomp() to play nice within a script that uses ARGV.

This script also prints a simple prompt to use in the script. The example is similar to a text based game (Zork or Adventure, anyone :)?). Also, I'm starting to get some strange issues with publishing my blog entries now because of the Ruby code interfering with Blogger's interface, so I'm going to copy the actual code details into image form (lets see if that resolves it).

OK, first thing (notice this from yesterday?), here's a change-up. gets.chomp() is represented as STDIN.gets.chomp(). Why? Because ARGV is being used. the default gets method will look in ARGV and try to read from the first variable. getting input straight from the keyboard (user input) is referred to in computer parlance as STDIN. So to read the users input, when ARGV is used, STDIN.gets is used. Cool, huh :)?

[here's what I wrote]

What You Should See

When you run this, remember that you have to give the script your name for the ARGV arguments.

[and here's what I get]

Extra Credit

Find out what Zork and Adventure were. Try to find a copy and play it.


Change the prompt variable to something else entirely.

[ prompt = "#{$0} >> " . Note this is performing string interpolation in the prompt. I don't k now why I'm mentioning it, I just think saying "string interpolation" is fun, really :) ]

Add another argument and use it in your script.

[Since I'm not sure how to enumerate the ARGV vartiable beyond the ARGV.first option given as an example, I've played coy and figured that if an array begins, it has to end, so I entered ARGV.last as an option (note, it's coincidence that  firstname corresponds to first and lastname corresponds to last, but that's not what they represent. They represent the first argument in the array and the final argument in the array]

[I get that string interpolation can take place with this example and within this format of multi-line printing, and that's pretty cool :) ].


Wow, I haven't see or heard about a text based adventure game since I was a kid in the late 70s or early 80s. That brings back memories. It also reminds me how cool the programming behind some simple question and answers could totaly suck you in. It was neat to see a reminder to how this was done, as well as to experiment with pulling in variables from the command line and within a script.
Post a Comment