develop with

Slice and Ranges

Get a subset of items or characters based on a range

Slicing is a way to get a subset of elements from an array or string. A string is a fancy array of characters.

To get a subset of elements in an array in ruby, use the range operator ...

Example:

word_numbers = ['one','two','three', 'four']
skip_first_number_list = word_numbers[1..-1]

Using -1 will get all the values until the end of the array. Since array indexes start with 0, using 1 in the above example skips the first element and returns the rest of the elements.

comments powered by Disqus

Want to see a topic covered? create a suggestion

Get more developer references and books in the developwith store.