Skip to content

Purogo UsingParameters

Thomas E. Enebo edited this page May 18, 2012 · 3 revisions

In the last section Purogo/ReducingRepetitionWithRuby we changed our hex program to draw a bigger hex. Wouldn't it be nice if we could just specify how big to make it when using our draw command? Let's do that now. Enter in this program as 'hex2':

turtle("is this a hexagon") do |*args|
  if args[0]
    length = args[0].to_i
  else
    length = 5
  end

  6.times do
    forward length
    turnleft 60
  end
end

Whoa! Quite a bit of new Ruby syntax, but don't worry I will walk you through it. Before we do though. Let's draw this with '/draw hex2'. Works just like the first time we drew our hex in the last section. '/undraw' this hex and let's try it again, but we will add a parameter value '/draw hex2 15'. Now notice this hex looks like the second hex we drew in the last section. Our new parameter just make our hex program much more useful. Now let's look at the new syntax:

turtle("is this a hexagon") do |*args|

'|*args|' is new on this line. What this means the args Array will accept any number of values and store them in args. So when we typed '/draw hex2 15', the args parameter ends up holding a single value of 15 (args = [15]). If we had typed '/draw hex2 15 dirt' then args would have two values (args = [15, "dirt"]). Let's continue:

  if args[0]
    length = args[0].to_i
  else
    length = 5
  end

Since most of you already know what an if/then/else statement is, then I will only cover this briefly. This snippet is asking the args Array if it has a value stored in the first spot in the array (0 or zeroth element of the Array). If so, then ask that value to become an integer value (args[0].to_i) and store it into a local variable named length. If there is no elements in the first spot of the Array then just set length to 5.

The last thing to be aware of is we are now using this length variable lower down in hex:

    forward length

Now we will go any length we pass in from the draw command. Let's continue by generalizing all polygons in Purogo/MoreRubyMoreFun.