The Ruby/JavaScript Array.slice() Variation

Any English speaker who as traveled to other English speaking regions has had the experience of encountering words that are sounded and spelled the same way but have different uses depending on your locality. Two words that come to mind right away are “mate” and “lift.” In the New York version of English of which I’m most familiar, these two words are verbs. To my friends in London, these two words are nouns. The context of the usage of these words often clarifies the discrepancy before too long. However, I was unaware that I would run into this issue using higher level programming languages in coding.

While coming up with simpler ways to answer typical coding challenge problems and making sure I could recreate the same result in both JavaScript and Ruby, I stumbled upon an issue with the common array function Array.slice() by accident. Since I work every day in both Ruby and JavaScript, I take for granted that many of the functions and methods operate in a very similar way. Therefore, it always came as a surprise that I had to continually lookup how to use .slice() — it would never stick in my mind. The reason turns out to be because they behave differently in Ruby and JavaScript.

The simple problem I was working on involved “Array Chunking. “ Array chunking is a technique whereby one takes a larger array and splits it into smaller array for various purposes. For example:

chunkSlice([2,7,3,5,23,4,11,66,8, 99],3)
// returns: [[2,7,3], 5,23,4], [11,66,8], [99]]

The way I solved this in JavaScript was to loop through the original array and cut out parts of it to push into a new array of sub arrays. As you can see from the code below, it’s a rather long-winded way of going about it. I thought I was being clever by checking where I needed to add another loop if there was a remainder (using the modulo % operator).

function chunkSlice(array, size) {
let result = []
let loops = parseInt(array.length / size)
if (array.length%size !== 0) loops++
for(let i = 0; i<loops; i++) {
result.push(array.slice(i*size, (size+(size*i))))
}
return result
}

As you can see in the JavaScript function, we are pushing into the result array a smaller array beginning at the loop index multiplied by the desired size of the sub array and ending at the array index which is the length of the size added to the starting index. The way I wrote this could have been simplified into:

result.push(array.slice(i, i + size))

However, when I went to try this in my Ruby version of the method, I was getting a much larger sub array than I wanted. What was going wrong?

According to Ruby.Doc.org, Element Reference — Returns the element at index, or returns a subarray starting at the start index and continuing for length elements, or returns a subarray specified by range of indices.

According to MDN Wed Docs, the Array.Slice() method works as follows: returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

Another way of visualizing this is:

JavaScript: 
.slice(indexToBeginAt, indexToEndAt - 1)
Ruby:
.slice(index_to_begin_at, number of elements to return)

Therefore, to get the proper result from Ruby we need only specify the starting index and then the size itself that we want. In a way this is a simpler use of .slice().

Here is the simplified result in Ruby:

def array_chunk(array, size)
result = []
index = 0
while array.length > index do
result.push(array.slice(index, size))
index += size
end
return result
end

So for those of you who are often straddled between the worlds of Ruby and JavaScript (just as those of you working with a Ruby on Rails backend with a React frontend), I hope this clears some things up.

Composer, playwright, designer for theater, jazz musician, philosopher. Recent Software Engineer graduate of Flatiron School in NYC.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store