Development Journal

Student at Flatiron School NYC

Keeping Sharp

As a novice programmer, I am constantly reminded of how I felt when training to play sports. To me, playing around with primitive objects such as arrays and strings is very much like playing wall ball in any sport. It is repetition of a core skill set.

Sort

Outside of the transformative enumerable methods such as .select and .map, arrays are responsive to a variety of methods that allow us to sort and manipulate them very quickly without passing the method a block.

As we add elements on top of an array’s stack with the push method. The items are ordered based on the sequence in which we pushed them onto the stack.

1
2
3
array = []
array.push(2,6,4,3,1,5)
array = [2,6,4,3,1,5]

In order to get a sorted copy of the array returned to us, we simply would need to type.

1
array.sort # => [1, 2, 3, 4, 5, 6]

but what if we wanted them sorted in a descending order. We can use a little method chaining here to produce the desired effect.

1
array.sort.reverse # => [6, 5, 4, 3, 2, 1]

chars

Often times we are passed a string or array and we need to break it apart at a chosen delimiter. The .chars method allows us to break apart a string into the individual characters. The return of this is an array of the individual characters.

1
2
test = "hello how are you"
test.chars # => ["h", "e", "l", "l", "o"," ", "h", "o", "w"," ", "a", "r", "e"," ", "y", "o", "u"]

excluding characters

Now that we have returned an array of each indiviudal character in the string, we may want to work with the new data but because we used the .chars method we also have " " character in our return array.

subtraction:

We have several options here such as using a .reject method call but I am going to touch on a simple way of doing this that I have used. We can subtract the characters we don’t want from the array. This works for any character as well and does not modify the reciever.

1
chars = test.chars # => ["h", "e", "l", "l", "o"," ", "h", "o", "w"," ", "a", "r", "e"," ", "y", "o", "u"]
1
chars - [" "] #=> ["h", "e", "l", "l", "o", "h", "o", "w", "a", "r", "e", "y", "o", "u"]

practice

There are many more basic work flows that I find myself repeating through out the semeester and it has helped me to be able to just run them quickly when I have some free time so that when presented with a task, it is second nature to move through a given work flow.

Next post I am going to go over a few simple ways to convert arrays into hashes with some concise and simple iterations.