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 up to, but not including index
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.
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]
slice(index) simply returns the value at
slice(begin) returns a new array starting from the value at the index
begin all the way through to end of the array.
String.slice that work the same as their respective array-based counterparts, but on characters in the string.
splice method. It’s just like
slice but it removes the selected values from the original array. It’s like Ruby’s
arr = [1,2,3,4,5] arr.slice!(1,1) # returns  arr # contains [1,3,4,5]
arr = [1,2,3,4,5]; arr.splice(1,1); // returns  arr; // contains [1,3,4,5]
Okay last example.
str = "hello" str.slice!(1,1) # returns "e" str # contains "hllo"
str = "hello"; str.splice(1,1);
TypeError: str.splice is not a function
And there are more differences than what I mentioned here. Ruby’s
splice can be used to insert values. And more! Check out the docs for details.