JavaScript’s slice syntax with two arguments:

str.slice(startingIndex, nonInclusiveEndingIndex)

'elephant'[3] // 'p' 'elephant'[6] // 'n' 'elephant'.slice(3, 6) // 'pha'

Ruby’s slice syntax with two arguments:

str.slice(starting_index, length)

'elephant'[3] #=> 'p' 'elephant'.slice(3, 3) #=> 'pha'

To emulate JavaScript’s way of specifying a beginning and an ending slicing indices, we can do the following:

str[starting_index...non_inclusive_ending_index]

'elephant'[3] #=> 'p' 'elephant'[6] #=> 'n' 'elephant'[3...6] #=> 'pha'

JavaScript’s slice syntax with one argument:

str.slice(startingIndexToGetRestOfTheStringFrom)

'elephant'[3] // 'p' 'elephant'.slice(3) // 'phant'

Ruby’s slice syntax with one argument:

str.slice(the_one_index_from_where_to_get_that_one_character_from)

'elephant'[3] #=> 'p' 'elephant'.slice(3) #=> 'p'

To emulate JavaScript’s way of slicing in Ruby, we can do the following:

str[starting_index_to_get_rest_of_the_string_from, -1]

'elephant'[3] #=> 'p' 'elephant'[3, -1] #=> 'phant'

Ruby’s #drop method

If we are dealing with arrays in Ruby, we can leverage the #drop method which will behave just like JavaScript’s slice method with a single argument.

['e', 'l', 'e', 'p', 'h', 'a', 'n', 't'].drop(3) #=> ['p','h','a','n','t']

Unfortunately, #drop is not a string method.

'elephant'.drop(3) #=> undefined method `drop' for "elephant":String

Sources

Slicing and Splicing: Ruby and JavaScript Gotchas: Basically the article I always google for whenever I was trying to not mix up my slice syntaxes from Ruby to JS and vise versa. Consider my post a cheatsheet version of this post with Ruby’s string[i..-1] and an aside on #drop thrown in.