El Code Snippet

Take and Use ... It's cool!

Ruby: Arrays

Arrays are a collection of values that are referenced by an index value. This collection is comma delimited and the position of each is assigned an index value. All array indices begin with 0 (zero). So, if the first value is 5, it index value is 0. If the third element in the array is 7, it's index is 2.

Let's take a look at an example.

Figure 1

Here we display a number of ways we can work with arrays.

    =begin
    all Ruby arrays begin at index 0 (zero)
    here's an example
    =end
    
    myArr = [5, 2.4, "hello world", true]
    
    # to access the second element (2.4), I have to make sure I reference index: 1 
    puts myArr[1]
    
    # if I want to add an element to the array, I can either use: 
    myArr << "8"
    
    # which will give me an array that looks like this:
    puts "#{myArr}"
    
    # or use the method: push()
    myArr.push(17)
    
    # and, so that when I call the last array (done with an index reference of: -1)
    # this is what is shown
    puts myArr[-1]
    
    puts "The entire array now looks like this: #{myArr}"
            

Which returns ...

Figure 2

Here is what the result of the code in Figure 1 looks like

    2.4
    [5, 2.4, "hello world", true, "8"]
    17
    The entire array now looks like this: [5, 2.4, "hello world", true, "8", 17]
    => nil
            

What's up with nil? Well, when there is nothing returned, nil shows up. In Ruby, nil is a special data type that literally means: nothing. You can think of it like a null value or a variable that has nothing assigned to it.

Dont' believe me? Hack the code yourself: https://repl.it/IiJX