Day 9 of Flatiron’s Software Engineering Bootcamp

Last week I was able to take advantage of my free time and attend a lot of real-time classes. I feel the classes helped me to really cement my understanding of common Ruby class methods, such as collect and select, and introduced more topics. I want to write about something that I learned, that was not covered in the lab material.

The Select Method

Using the select method to return all even numbers in an array.
Using the select method to return all even numbers in an array.

The select method returns an array containing those elements for which the block returns a true value.

The purpose of the select_even_numbers method is to only select (see what I did there?) or choose the even numbers from the array that is passed into the method. If you were to run the code above, you would get the original array as a return value because the original array was not modified. A new array was formed behind the scenes, but we are not returning it.

Ultimately we are returning the original array that was passed in, array_of_numbers. If we deleted array_of_numbers on line 9, our method would return a new array (thanks to the select method) with 2, 4, 6 and 8 as values.

The Bang Operator

Using the bang operator on the select method to modify the original array.
Using the bang operator on the select method to modify the original array.

The code above implements the select method with a bang operator (!) on the end. When we run the code above, we will be returning the original array like we did previously. However, this code will modify the object that it is called on. When we return array_of_numbers, it will contain 2, 4, 6 and 8. When we utilize the numbers variable from now on, it will only contain 2, 4, 6 and 8. The array has been mutated and the original value(s) are no longer accessible.

Upon further research, Ruby considers the example about, and others, “dangerous methods” because they permanently change the object that the variable points to. I found the concept very interesting because it gives me a variable containing the return values that I can continue to modify as needed elsewhere in my code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.