Monday 9 December 2013

Learn Ruby Language and Be an exploit coder-13

Parameters, Unpacking, Variables

In this lesson we will cover one more input method you can use to pass variables to a script (script being another name for your .rb files). You know how you type ruby exploit13.rb to run the exploit13.rb file? Well the exploit13.rb part of the command is called an "argument". What we'll do now is write a script that also accepts arguments.

Type this program and I'll explain it in detail.
  • first, second, third = ARGV 

  • puts "The script is called: #{$0}"
  • puts "Your first variable is: #{first}"
  • puts "Your second variable is: #{second}"
  • puts "Your third variable is: #{third}"

The ARGV is the "argument variable", a very standard name in programming, that you will find used in many other languages. It's in all caps because it's a constant, meaning you shouldn't change the value once it's been assigned. This variable holds the arguments you pass to your Ruby script when you run it. In the exercises you will get to play with this more and see what happens.

Line 1 "unpacks" ARGV so that, rather than holding all the arguments, it gets assigned to three variables you can work with: first, second, and third. The name of the script itself is stored in a special variable $0, which we don't need to unpack. This may look strange, but "unpack" is probably the best word to describe what it does. It just says, "Take whatever is in ARGV, unpack it, and assign it to all of these variables on the left in order."

After that we just print them out like normal.

What You Should See.

Run the program like this.

  • ruby exploit13.rb first 2nd 3rd

 This is what you should see when you do a few different runs with different arguments.

  • $ ruby exploit13.rb first 2nd 3rd
  • The script is called: exploit13.rb
  • Your first variable is: first
  • Your second variable is: 2nd
  • Your third variable is: 3rd
  • $ ruby exploit13.rb cheese apples bread

  • The script is called: exploit13.rb
  • Your first variable is: cheese
  • Your second variable is: apples
  • Your third variable is: bread

  • $ ruby exploit13.rb InnoXent | StoKer
  • The script is called: exploit13.rb
  • Your first variable is: innoXent
  • Your second variable is: |.
  • Your third variable is: Stoker

You can actually replace "first", "2nd", and "3rd" with any three things. You do not have to give these parameters either, you can give any 3 strings you want.


  • ruby exploit13.rb stuff I like
  • ruby exploit13.rb anything 6 7 

Extra Credit

Try giving fewer than three arguments to your script. What values are used for the missing arguments?
Write a script that has fewer arguments and one that has more. Make sure you give the unpacked variables good names.
Combine STDIN.gets.chomp() with ARGV to make a script that gets more input from a user.

No comments:

Post a Comment