Submit Your Article


 
RPG Maker

Welcome Guest ( Log In | Register )


  Games Resources RPG Maker VX RPG Maker XP Scripts Tutorials Downloads

> [Scripting][Series]The Scripter’s Journey Series, 4. Arrays and Hashes!!
The Law G14
post Jun 29 2012, 08:28 PM
Post #1


Scripter FTW
Group Icon

Group: Local Mod
Posts: 1,346
Type: Scripter
RM Skill: Skilled
Rev Points: 5




The Scripter’s Journey Series

4. Arrays and Hashes!!


Table of Contents
I. What the heck are containers?!
II. In-depth Analysis on Arrays!
III. Hash-Time!
IV. Conclusion!


What the heck are Containers?!
What the heck is a container?! Well, that’s what this lesson is all about today. Well as we talked about in the first tutorial, everything is an Object (we’ll get more in-depth with this in two lessons from now), well containers are essentially Objects that contain other objects (yea, yea, objectception, I know). It’s really that simple. Ruby has two innate “container” type Objects (or classes which again we’ll cover in two lessons from now) , Arrays and Hashes.


In-Depth Analysis on Arrays!
So, you’re in a high school hallway and you see rows and rows of lockers running down. Let’s say in a hypothetical situation each locker was assigned a number from 0 to how many lockers there were (let’s say there were five lockers), and each locker had exactly one item. Lets call this hallway an array named “hallway” (without the quotations). So here’s the code for this hallway array thus far:

CODE
hallway = [“English Textbook”, “Planner”, “Job Application”, “Multiplication Table”, “Money”]


Ok, let’s review this code. First of all, we established an array much the same as you would establish a variable, by first naming your array (always in lower case!) and then using the assignment operator ( = sign ). After that you use square brackets ( [ ] ), and then enclose inside these brackets the Objects that will be contained. Each Object is separated by a simple comma ( , ). In our example, however, each Object is an item in the locker in this hallway. We have an English Textbook, a Multiplication Tablet, etc. Now an important note, arrays can contain any Object and also they can contain variables. Consider the following:

CODE
var = 5
array1 = [var, 6, 7, 8]


So, now you’re wondering “Ok, so these array things can contain Objects for me like Integers, Booleans, and they can even contain stuff like arrays…but how does this help me again?” Alright, well, let’s get to that. Remember at the beginning of the story I said that each locker would be assigned a number from 0 to the number of lockers? Well, this is important, let’s check out the following example:

CODE
hallway = [“English Textbook”, “Planner”, “Job Application”, “Multiplication Table”, “Money”]
print hallway[0]


This code would print out “English Textbook”. In order to access each individual Object of an array, you must use the subscript operator ( [] ) right next to the array name. The first item or Object of an array always is item #0. The last item is always the number of Objects in the array minus 1:

CODE
hallway = [“English Textbook”, “Planner”, “Job Application”, “Multiplication Table”, “Money”]
print hallway[4]
# Prints ‘Money’

These numbers in the subscript operators are called indexes. So basically, to obtain one of those Objects, you would put it’s index in the subscript operator and side that next to the array name like the above two examples. Now, finding the index of an Object in an array can sometimes be confusing to new learners. Here’s how to think about:

First item in array = Index of 0
Second item in array = Index of 1
So on and so on
Last item in array = Size of array (how many objects are in it) – minus 1. This is because the first item starts on an index of 0 not 1 (I don’t know why they made it like this, but we have deal with it).

So let’s show one final example:

CODE
booleans = [true, false, false, true, true]
print booleans[2] # prints “false”


Now that we know how to build arrays and reach certain Objects in an array by putting their index in the subscript operator, let’s combine arrays with the for loops we learned last tutorial!
CODE
hallway = [“English Textbook”, “Planner”, “Job Application”, “Multiplication Table”, “Money”]
for i in hallway
print i
end


Arrays are treated as “ranges” like we discussed last time, “i” is equal to each Object of the array in each iteration. So therefore this piece of code would print out every object; try it out and see for yourself!

Another way you can display loops with an array is specifically providing the range like so:

CODE
hallway = [“English Textbook”, “Planner”, “Job Application”, “Multiplication Table”, “Money”]
for i in 0…hallway.size
print hallway[0]
end


Now if you remember from the last tutorial three dots means it excludes the last number (remember, you add something, a dot, and you lose something, the last number) and this is because there is no array element of “hallway[5]”, the last Object in the array is “hallway[4]” because as I said earlier this tutorial, arrays start on zero, so that means the last index is going to be one less than the array’s size (or the number of Objects it holds.

Sidenote: Each Object in an array is known in the politically correct way as an “element”. You can treat array elements as variables and assign them to new values. For example if you write a line “hallway[0] = 1”, that element would no longer be “English Textbook”, but would not be an Integer value. So you can treat each element as a variable.

Last thing to talk about is some common methods you can use on arrays. We already talked about “size”, but you can also use “push”.

CODE
hallway.push(“Math Textbook”)


Simply put, “push” allows you to add another “element” to your array, with a new index and everything. There is also “pop” which removes the last element of the array, and “shift” which removes the first element and brings the rest of the elements an index closer to fill in the gap.


Hash-Time!
Alright, let me just get this out of my stomach, but for some odd reason I just love hashes :/ Hopefully you all will too after this section is all said and done! Well, hashes are very much like arrays. They’re both containers, and they both contain Objects and variables. However, the key difference is the method of accessing Objects within the hash. In arrays you just put the index in the subscript operator and boom! However, with hashes, every Object in the hash has a “key” and this key helps you “unlock” or access this value (or Object).

Array Form
CODE
array[0] = Object


Hash Form
CODE
hash[“Johnny”] = Object/value


As you can see, the “key” can be any Object! Think of it as a line of treasure chests. Each treasure chest needs a specific key for it to be “unlocked” or accessed. Let’s say one key was a boolean (like true or false), another could be a String (like “Johnny”), etc.

Now, here’s how you build hashes, their keys, and their values!

CODE
hash1 = {“Johnny” => 0, “Bill” => 2, “Jonas” => 1}


Now first of all, we can see here that we don’t use square brackets, but curly brackets. Also, each key comes before the => sign, and each value or Object comes after, to separate these you have commas. In this example, we have the keys being the employee’s name (random example), and the values being their employee ID.

Now that we have that understand, let’s wrap up a key concept that needs to be understood in both arrays and hashes. First of all, when you build an array or hash you don’t have to supply all the elements within at the time of construction, in fact, you generally won’t do this. Usually, you’ll simply do this:

CODE
array1 = []
hash1 = {}


Now, like I said in the sidenote, elements can be treated as a variable. In fact, this is usually how it’s expressed in normal documentation. You would usually leave the array and hash blank like so and later on provide the Objects:

CODE
array1 = []
hash1 ={}
array[0] = “Bill”
hash1[“Bill”] = 0


When done like this, it can easily be seen how arrays and hashes can be used as variables in this sense. But don’t get confused, just keep it simple in your head and know that arrays store a multitude of Objects and reference them through the use of indexes. Hashes also store several Objects and reference them through using keys and values (Objects). However, when built in a blank state (like in the above example where you don’t predefine any Objects to that array or hash) then you can treat them as variables. And even if this isn’t done, you can still individually change Objects within an array or even a hash like how I explained it in the sidenote.

Finally, before we leave hashes, I’ll give a brief explanation on how to use for loops with hashes. Basically, you can either loop through the keys or loop through the values (Objects).

CODE
for i in hash1.keys
print i
end
for i in hash1.values
print i
end


And that’s all there is too it!


Conclusion
So from this tutorial you’ve learned “container” type Objects. These Objects are able to “contain” other Objects. Ruby has two built-in Containers and they are arrays and hashes. They’re both pretty similar except mainly the way their elements or Objects are accessed. Arrays are accessed through indexes while hashes are accessed through key and value pairs. Furthermore you can use both with for loops and finally arrays and hashes can both be used in a “variable” sense and be assigned new values or Objects. Next time we got methods!

The order of how these tutorials will progress: http://www.rpgrevolution.com/forums/index....showtopic=54953

~Law


__________________________

To put in sig, copy this link:
CODE
[url="http://www.rpgrevolution.com/forums/index.php?showtopic=51540"][img]http://img40.imageshack.us/img40/6504/conceptthelawbanner.png[/img][/url]


Sig Stuff


"When you first come, no one knows you. When help them out, they all know you. When you leave, they all love you. When you come back, they've already forgotten you." -- copy into your sig if you think this quote speaks true!

If you are one of the very few teenagers that know what real rap is and don't blindly listen to the hate statements (rap is crap), then put this in your sig. I say this in the name of Common, Mos Def, Lupe Fiasco, 2Pac, Nas, Talib Kweli, Eminem, and many others. -Exiled One

My Project Thread: Gai's Hunters


Go to the top of the page
 
+Quote Post
   

Posts in this topic


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 18th May 2013 - 02:11 PM
RPG RPG Revolution is an Privacy Policy and Legal
eXTReMe Tracker