Project Ramon

A learning journey from a Ruby noob perspective

Arrays and Parallel Assignment

koans1_header_img

It was brought to my attention recently that I don’t have a solid enough grasp on the fundamentals of Ruby. This is contributing to a lot of confusion on my part while pairing.  As a way to combat this obstacle, I am going to pause on my projects for a couple of weeks and focus on all the exercises on Ruby Koans. This will definitely help me in the programming confidence department, and also allow me to better comprehend whats happening in a Rails application. It would be mighty difficult to try and read a book without being rock solid in first processing words, and eventually  being able to gather meaning  from paragraphs.

So here I go!

Today I wanted to briefly cover arrays and parallel asignment

About Array Assignments

I first learned this from a book titled The Well-Grounded Rubyist, and as I have never used it in production, thought that it would be a good way to start off.

We can assign variable names to array indexes like so:

Line 2 is how an entire array can be stored into one variable, and line 5 illustrates a way to store specific indexes into multiple variable names using one line of comma separated variables for index-by-index assignment.

Both the buick and chevy variables contain values for the [0] and [1] indexed array values respectively. In the case above, the * or splat operator before our audi variable means that *audi will collect the remaining values of the original array and store them as a new array.

Trying this technique with three variables and an array of only two indexes can be done, but the value stored in the third variable will be nil.
Here’s an example of this in action:

We can also assign sub-arrays with this technique like so:

This technique works no matter which index the sub-array is contained in.

I hope that these illustrations have offered as much insight to you as they have for me.

Advertisements

Categories: AirPair, Newbie, Ruby

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s