Slicing and Splicing: Ruby and Javascript Gotchas

Ruby and Javascript both have a method called slice. They looks similar but they work differently. Let’s look at some examples.

Guess what the following Ruby code returns.


And it returns…


It’s a new array containing the first 2 values of the calling array starting from index 0.

What about this Javascript?



Javascript returns an array with the values starting from index 0 up to, but not including index 2.

I know. It looks the same. But don’t fall for it. Here’s another example that actually shows this difference.



[3, 4, 5]




In Ruby the method is slice(start, length) where start is the starting index, length is the number of values to take up to.

In Javascript the method is slice(begin, end) where begin is, again, the starting index, but end is the index to take up to, non-inclusive.

slice also has a single argument format






[3, 4, 5]

Here, Ruby’s slice(index) simply returns the value at index.

And Javascript’s slice(begin) returns a new array starting from the value at the index begin all the way through to end of the array.

Ruby and Javascript both also have String.slice that work the same as their respective array-based counterparts, but on characters in the string.





Javascript also has a splice method. It’s just like slice but it removes the selected values from the original array. It’s like Ruby’s slice! method.


arr = [1,2,3,4,5]
arr.slice!(1,1)     # returns  [2]
arr                 # contains [1,3,4,5]


arr = [1,2,3,4,5];
arr.splice(1,1);     // returns  [2]
arr;                 // contains [1,3,4,5]

Okay last example.


str = "hello"
str.slice!(1,1)     # returns  "e"
str                 # contains "hllo"


str = "hello";

TypeError: str.splice is not a function

Whoops! There’s no built-in String.splice method in Javascript. Arrays only!

If you have to switch between Ruby and Javascript a lot, be careful out there and always keep your methods straight.

And there are more differences than what I mentioned here. Ruby’s slice methods can take a range value as a parameter. Javascripts splice can be used to insert values. And more! Check out the docs for details.