Ruby Operators and Arrays - Running for Precedence
(Page 2 of 4 )
Never mind that next year is an election year in the US; we're talking about precedence, not presidents. And no, not the lawyer's form of precedence either (Row vs. Boat anyone?)
Mathematical operators, and programming operators for that matter, have a thing called precedence, which tells the mathematician (or the program in this instance) in what sequence the mathematical problem should be solved. In Ruby, if left to its own devices, this is determined by the operator. For instance, if Ruby sees the following equation: 1+1 * 2 it will give the result of three, instead of the four that we were looking for. This is because to Ruby, the multiplication takes precedence over the addition.
Fixing this is as easy as pie. Not making pie, mind you, which isn't that easy, but eating pie, which, judging by my increasing pants size, is fairly easy. It's especially easy if you remember how you showed precedence in math class. All you need to do is add parentheses to the part of the equation you wish to take precedence: (1+1) *2. This would result in the answer we were seeking, which is four.
Arrays
Arrays are storage devices for a multitude of data. Arrays hold more than one variable, using an index number to identify each one. The syntax for creating an array is as follows:
array = [100, 150, 200]
Now let's say you wanted to print out the data held in each array. You would do that using the index number of each variable, as shown below:
puts array[0]
puts array[1]
puts array[2]
This will print out:
100
150
200
You will note that the first array index number is 0. This is always the case. Another way to assign values to an array is like this:
array[0] = "ted"
array[1] = "bob"
array[3] = "billy"
As you can see, you can also store text inside of an array (because you can store text inside a variable). You can also mix and match.
array[0] = "Ted"
array[2] = 1
array[3] = 1.4
You might note that in the above example I skipped defining the [1] index. That's okay. I can always define it later on if I like. Also, if you want to print everything within an array, you can use puts on it. (Do not confuse this word with putz, which is something completely different and could get you severely injured if said to the wrong person).
Array = ["Hey" "You" "Get" "Into" "My" "Car"]
puts array
This would print out the following:
Hey
You
Get
Into
My
Car
It would also get that song stuck in my head for the next week.
Unlike traditional programming languages, Ruby does not use multi-dimensional arrays. Instead, it uses two-array indices, which is beyond the scope of this tutorial. Basically with two-array indices, the first index represents the start location, and the second stores the number of elements you want to modify.
Next: Hashes >>
More Ruby-on-Rails Articles
More By James Payne