Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 4

# 3.0 Introduction to Arrays Empty arrays ============ It is easier than you think.

There is a [] typed into the code editor already. This is how you create an arra y. Example Code: [] You can also do the same thing by Array.new. Example Code: Array.new Building arrays =============== You can create an array with a set of values by simply placing them inside [] li ke this: [1, 2, 3]. Try this out by creating an array with the numbers 1 through 5, inclusive. [1,2,3,4,5] Arrays in Ruby allow you to store any kind of objects in any combination with no restrictions on type. Thus, the literal array [1, 'one', 2, 'two'] mixes Intege rs and Strings and is perfectly valid. Looking up data in Arrays Looking up values within an array is easily done using an index. Like most langu ages, arrays in Ruby have indexes starting from 0. The example below demonstrate s how to look up the third value in an array. Example Code: [1, 2, 3, 4, 5][2] Now it's your turn - extract the 5th value from the array below. Remember that t he nth value in an array has an index of n-1. [1, 2, 3, 4, 5, 6, 7][4] Array indexes can also start from the end of the array, rather than the beginnin g! In Ruby, this is achieved by using negative numbers. This is called reverse i ndex lookup. In this case, the values of the index start at -1 and become smalle r. The example below returns the first value in the array. Example Code: [1, 2, 3, 4, 5][-5] Go ahead on try it out - extract the last value from the array below. [1, 2, 3, 4, 5][-1] Growing arrays ============== In Ruby, the size of an array is not fixed. Also, any object of any type can be added to an array, not just numbers. How about appending the String "woot" to an array? Try using << - that's the 'append' function - to add it to the array bel ow. [1, 2, 3, 4, 5] << "woot"

Unlike many other languages, you will always find multiple ways to perform the s ame action in Ruby. To append a new element to a given array, you can also use p ush method on an array. Add the string "woot" to given array by calling push. [1, 2, 3, 4, 5].push("woot") Using '<<' is the most common method to add an element to an Array. There are ot her ways as well, but we will touch upon them later. # 3.1 Basic Array Operations Transforming arrays =================== Now on to more interesting things, but with a little tip from me first. Try runn ing this: Example Code: [1, 2, 3, 4, 5].map { |i| i + 1 } You'll notice that the output, [2, 3, 4, 5, 6] is the result of applying the cod e inside the curly brace to every single element in the array. The result is an entirely new array containing the results. In Ruby, the method map is used to tr ansform the contents of an array according to a specified set of rules defined i nside the code block. Go on, you try it. Multiply every element in the array bel ow by 3 to get [3, 6 .. 15]. [1, 2, 3, 4, 5].map { |i| i*3} Ruby aliases the method Array#map to Array#collect; they can be used interchange ably. The Class#method syntax is the standard way of referring to Ruby methods a nd you will see it a lot in this book. Filtering elements of an Array Filtering elements in a collection according to a boolean expression is a very c ommon operation in day-to-day programming. Ruby provides the rather handy select method to make this easy. Example Code: # select even numbers [1,2,3,4,5,6].select {|number| number % 2 == 0} The method select is the standard Ruby idiom for filtering elements. In the foll owing code, try extracting the strings that are longer than five characters. names = ['rock', 'paper', 'scissors', 'lizard', 'spock'].select {|x| x.length > 5} Deleting elements ================= One of the reasons Ruby is so popular with developers is the intuitiveness of th e API. Most of the time you can guess the method name which will perform the tas k you have in your mind. Try guessing the method you need to use to delete the e lement '5' from the array given below: [1,3,5,4,6,7].delete 5 I guess that was easy. What if you want to delete all the elements less than 4 f rom the given array. The example below does just that: Example Code:

[1,2,3,4,5,6,7].delete_if{|i| i < 4 } You'll notice that Ruby methods with multiple words are separated by underscores (_). This convention is called "snake_casing" because a_longer_method_looks_kin d_of_like_a_snake. Okay! Hands-on time. Delete all the even numbers from the array given below. [1,2,3,4,5,6,7,8,9].delete_if {|i| i%2 == 0} Doing this in languages like C or Java would take you a lot of boiler plate code . The beauty of Ruby is in its concise but readable code. # 3.2 Iteration Got `for` loops? ================ Ruby, like most languages, has the all-time favourite for loop. Interestingly, n obody uses it much - but let's leave the alternatives for the next exercise. Her e's how you use a for loop in Ruby. Just run the code below to print all the val ues in the array. Example Code: array = [1, 2, 3, 4, 5] for i in array puts i end Ok, your turn now. Copy the values less than 4 in the array stored in the source variable into the array in the destination variable. def array_copy(source) destination = [] # destination = source.select {|x| x < 4} for i in source if i < 4 destination << i end end return destination end Iteration is one of the most commonly cited examples of the usage of blocks in R uby. The Array#each method accepts a block to which each element of the array is passed in turn. You will find that for loops are hardly ever used in Ruby, and Array#each and its siblings are the de-facto standard. We'll go into the relativ e merits of using each over for loops a little later once you've had some time t o get familiar with it. Let's look at an example that prints all the values in a n array. Example Code: array = [1, 2, 3, 4, 5] array.each do |i| puts i end Ok, now let's try the same thing we did with the for loop earlier - copy the val ues less than 4 in the array stored in the source variable to the array in the d estination variable. def array_copy(source)

destination = [] source.each do |i| if i < 4 destination << i end end return destination end

You might also like