Slices in Ruby

Ruby doesn’t have a direct equivalent to Go’s slices, but we can use arrays to demonstrate similar concepts. Ruby arrays are dynamic and can grow or shrink as needed.

# Unlike Go slices, Ruby arrays are typed by the class Array
# and can contain elements of different types.
# An uninitialized array is empty but not nil.
s = []
puts "uninit: #{s} #{s == nil} #{s.length == 0}"

# To create an empty array with non-zero length, we can use Array.new
s = Array.new(3)
puts "emp: #{s} len: #{s.length} cap: #{s.size}"

# We can set and get just like with Go slices
s[0] = "a"
s[1] = "b"
s[2] = "c"
puts "set: #{s}"
puts "get: #{s[2]}"

# length returns the length of the array as expected
puts "len: #{s.length}"

# Ruby arrays have a push method which is similar to Go's append
s.push("d")
s.push("e", "f")
puts "push: #{s}"

# We can also use the shovel operator (<<) to append elements
s << "g"
puts "shovel: #{s}"

# Arrays can be copied using the clone method
c = s.clone
puts "clone: #{c}"

# Ruby also supports array slicing with a similar syntax
l = s[2..4]
puts "sl1: #{l}"

# This slices up to (but excluding) index 5
l = s[0...5]
puts "sl2: #{l}"

# And this slices from index 2 to the end
l = s[2..]
puts "sl3: #{l}"

# We can declare and initialize an array in a single line
t = ["g", "h", "i"]
puts "decl: #{t}"

# Ruby doesn't have a built-in slices package, but we can compare arrays
t2 = ["g", "h", "i"]
puts "t == t2" if t == t2

# Ruby arrays can be multi-dimensional and jagged
two_d = Array.new(3) { |i| Array.new(i + 1) { |j| i + j } }
puts "2d: #{two_d}"

When you run this Ruby script, you’ll see output similar to the following:

uninit: [] false true
emp: [nil, nil, nil] len: 3 cap: 3
set: ["a", "b", "c"]
get: c
len: 3
push: ["a", "b", "c", "d", "e", "f"]
shovel: ["a", "b", "c", "d", "e", "f", "g"]
clone: ["a", "b", "c", "d", "e", "f", "g"]
sl1: ["c", "d", "e"]
sl2: ["a", "b", "c", "d", "e"]
sl3: ["c", "d", "e", "f", "g"]
decl: ["g", "h", "i"]
t == t2
2d: [[0], [1, 2], [2, 3, 4]]

Note that while Ruby arrays are different from Go slices in many ways, they serve a similar purpose as dynamic, resizable collections. Ruby arrays are more flexible, allowing elements of different types, but they don’t have the same performance characteristics or memory layout as Go slices.

Ruby’s array methods like push, pop, shift, and unshift provide similar functionality to Go’s slice operations. The array slicing syntax in Ruby is also quite similar to Go’s, making it easy to work with subarrays.

Remember that Ruby arrays are objects with many built-in methods, which can often replace the need for utility functions like those found in Go’s slices package.