

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Array slice function in Ruby
Sometimes we may want to exact a portion from an array data and perform some operation on it. In Ruby, we can do that with the help of the slice() function that takes two arguments, both of them indices, that are used to define a subsequence which then can be extracted from the array.
Syntax
The syntax of the slice() function is shown below −
res = Array.slice(x,y)
Here, x and y denote the starting index and the ending index, respectively.
Example 1
Now that we know a little about the slice() function on arrays, let's take a couple of examples and see how to use it in a program. Consider the code shown below.
# declaring the arrays first_arr = [18, 22, 34, nil, 7, 6] second_arr = [1, 4, 3, 1, 88, 9] third_arr = [18, 23, 50, 6] # slice method example puts "slice() method result : #{first_arr.slice(2, 4)}\n" puts "slice() method result : #{second_arr.slice(1, 3)}\n" puts "slice() method result : #{third_arr.slice(2, 3)}\n"
Output
When we execute this code, it will produce the following output −
slice() method result : [34, nil, 7, 6] slice() method result : [4, 3, 1] slice() method result : [50, 6]
Example 2
Let's take another example. Here, instead of integer values, we will take arrays of strings. Consider the code shown below.
# declaring array first_arr = ["abc", "nil", "dog"] second_arr = ["cat", nil] third_arr = ["cow", nil, "dog"] # slice method example puts "slice() method result : #{first_arr.slice(1, 3)}\n" puts "slice() method result : #{second_arr.slice(1, 2)}\n" puts "slice() method result : #{third_arr.slice(1)}\n"
Output
It will produce the following output −
slice() method result : ["nil", "dog"] slice() method result : [nil] slice() method result :
- Related Questions & Answers
- Array shift function in Ruby
- JavaScript Array slice()
- Array slice() in JavaScript
- Transpose() function in Ruby Programming
- MongoDB slice array in populated field?
- MongoDB Aggregation to slice array inside array
- Array reverse() vs reverse! in Ruby
- String reverse vs reverse! function in Ruby
- Find Max Slice Of Array | JavaScript
- Empty Slice vs. Nil Slice in Golang
- Array push(), pop() and clear() functions in Ruby
- How to slice an array with wrapping in JavaScript
- MongoDB query to slice only one element of array
- How to Get a slice of a primitive array in Java?
- Comparable module in Ruby