ruby slices are subsets. A slice can be a subset of an array, list or string. You can take multiple slices out of a string, each as a new variable.

A slice is never longer than then the original variable. This makes sense, if you take a slice of a pizza you don’t suddenly have two pizzas. In programming it’s similar.

Download Free Ruby Ebook

Slices in ruby

Example

The ruby code will take a slice out of a list of numbers.

Start by creating a list of numbers (myset). Then take a slice by specifying the lower and upper bounds. In programming languages the lower bounds is zero (arrays start at 0).

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/ruby

# define set
myset = Array[0,1,2,3,4,5,6,7,8,9]

# take slice
s = myset[0..3]

# output
puts s.join(' ')

The above program takes a slice and outputs it.

1
[0 1 2 3]

String slicing

ruby strings can be sliced too. The resulting slice will then also be a string, but of smaller size.

When slicing, remember that the index 0 is the first character of the string. The last character is the numbers of characters minus 1.

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/ruby

# create string
myStr = String.new("Ruby programming language")

# take slice
s = myStr[0..4]

# output
puts s

Exercises

  1. Take the string ‘hello world’ and slice it in two.
  2. Can you take a slice of a slice?