Array – An array representing the list of data in your program. When you have data in an array, you can sort, delete duplicates, reverse the order, extract elements, or search for specific data in the array. You can also convert an array to a string, convert an array into another array, and turn an array into a single value. In this tutorial, you will explore some of the most common methods Ruby provides to work with arrays.
1. Access to an element
If you’ve followed the How To Work with Arrays in Ruby tutorial, you already know how to access an element in an array using its index, starting with 0, for example:
1 2 3 4 5 | sharks = ["Tiger", "Great White", "Hammerhead", "Angel"] sharks[0] # "Tiger" sharks[1] # "Great White" sharks[-1] # "Angel" |
first & last
: You can also call the terminal element by the first & last method:
1 2 3 4 | sharks = ["Tiger", "Great White", "Hammerhead", "Angel"] sharks.first # "Tiger" sharks.last # "Angel" |
fetch
: when you access an element that does not exist, you will get the value nil. But if you want to return an error, you can use the fetch method:
1 2 3 4 | sharks.fetch(42) Output IndexError: index 42 outside of array bounds: -4...4 |
If you want to create a default for an element that doesn’t exist, you can do the following:
1 2 3 | sharks.fetch(42, "Nope") # "Nope" |
2. Retrieve multiple elements
Many times you want to retrieve a subset of elements from an array instead of just one. If you specify a starting index, then the number of elements you want, you will get a new array containing those values. For example:
1 2 3 | sharks = ["Tiger", "Great White", "Hammerhead", "Angel"] sharks[1,2] # ["Great White", "Hammerhead"] |
slice
: You can also useslice
to do the same thing:
1 2 3 | sharks = ["Tiger", "Great White", "Hammerhead", "Angel"] sharks.slice(1,2) # ["Great White", "Hammerhead"] |
The slice
method also returns a new array, without changing the original array. However, if you want to change, you can use the slide!
method slide!
take
: allows you to get the specified number of elements from the beginning of an array:
1 2 3 | sharks = ["Tiger", "Great White", "Hammerhead", "Angel"] sharks.take(2) # ["Tiger", "Great White"] |
3. Randomly retrieve an element from an array
Randomly picking an element from the array can be applied when you are building a random game, …
sample
:
1 2 3 4 5 6 | answers = ["Yes", "No", "Maybe", "Ask again later"] print answers.sample Output Maybe |
sample
can take a number of arguments as an argument, for example:
1 2 3 4 5 6 7 | sharks = ["Hammerhead", "Great White", "Tiger", "Whale"] sample = sharks.sample(2) print sample Output ["Whale", "Great White"] |
4. Search, filter elements
When you want to search for specific elements in an array, you often repeat the conditions until you find them. But Ruby has provided methods to simplify the search process.
include?
: looks for the presence of an element in the array, returns true / false:
1 2 3 4 | sharks = ["Hammerhead", "Great White", "Tiger", "Whale"] sharks.include? "Tiger" # true ["a", "b", "c"].include? 2 # false |
Note, include?
Requires an exact condition, for example:
1 2 3 4 5 | sharks = ["Hammerhead", "Great White", "Tiger", "Whale"] sharks.include? "Tiger" # true sharks.include? "tiger" # false sharks.include? "ti" # false |
find
: locate and return the first element that satisfies the condition
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | sharks = ["Hammerhead", "Great White", "Tiger", "Whale"] result = nil sharks.each do |shark| if sharks.include? "a" result = shark break end end sharks = ["Hammerhead", "Great White", "Tiger", "Whale"] result = sharks.find {|item| item.include?("a")} print result Output Hammerhead |
find
executes the block of code you provide for each element in the array. If the last expression in the block is true
, find
returns the correct value and stops the loop. If no results are found, then after iterating through all the elements it returns nil
.
select
: is similar tofind
, except that it returns a new array containing all of the conditions, otherwise it returns an empty array.
1 2 3 4 5 6 7 | sharks = ["Hammerhead", "Great White", "Tiger", "Whale"] results = sharks.select {|item| item.include?("a")} print results Output ["Hammerhead", "Great White", "Whale"] |
reject
: opposite ofselect
1 2 3 4 5 6 7 | sharks = ["Hammerhead", "Great White", "Tiger", "Whale"] results = sharks.reject {|item| item.include?("a")} print results Output ["Tiger"] |
Both select
and reject
do not change the original array value, if you want, you can use select!
or reject!
find_all
: alias ofselect
, but does not existfind_all!
5. Arrange the array
reverse
: reverse the array
1 2 3 4 5 6 7 | sharks = ["Angel", "Great White", "Hammerhead", "Tiger"] reversed_sharks = sharks.reverse print reversed_sharks Output ["Tiger", "Hammerhead", "Great White", "Angel"] |
reverse
does not change the original array, there is a reverse!
method reverse!
will change the original array
sort
: sort arrays in ascending order
1 2 3 4 5 6 7 | sharks = ["Tiger", "Great White", "Hammerhead", "Angel"] sorted_sharks = sharks.sort print sorted_sharks Output ["Angel", "Great White", "Hammerhead", "Tiger"] |
sort_by
: sort with given conditions
1 2 3 4 5 6 7 8 9 10 11 | sharks = [ {name: "Hammerhead"}, {name: "Great white"}, {name: "Angel"} ] sorted_sharks = sharks.sort_by{|shark| shark[:name] } print sorted_sharks Output [{:name=>"Angel"}, {:name=>"Great white"}, {:name=>"Hammerhead"}] |
Both sort
and sort_by
do not change the original array, if you want you can use sort!
or sort_by!
6. Delete the duplicate elements
uniq
:
1 2 | [1,2,3,4,1,5,3].uniq # [1,2,3,4,5] |
- For two arrays:
1 2 3 4 5 6 7 8 9 10 11 12 | sharks = ["Tiger", "Great White"] new_sharks = ["Tiger", "Hammerhead"] sharks + new_sharks # ["Tiger", "Great White", "Tiger", "Hammerhead"] sharks | new_sharks # ["Tiger", "Great White", "Hammerhead"] sharks = ["Tiger", "Great White"] new_sharks = ["Tiger", "Hammerhead"] sharks - new_sharks # ["Great White"] |
7. Data conversion
The map
and collect
(alias of map) methods can transform the contents of an array, meaning that it can perform an operation on each element in the array.
For example, you can use map
to perform arithmetic on each element in an array and create a new array containing new values:
1 2 3 4 5 6 7 8 9 10 | numbers = [2,4,6,8] # square each number squared_numbers = numbers.map {|number| number * number} print squared_numbers Out put [4, 16, 36, 64] |
map
often used in web applications to convert an array into elements for HTML lists. For example:
1 2 3 4 5 6 7 8 9 | sharks = ["Hammerhead", "Great White", "Tiger", "Whale"] options = sharks.map {|shark| "<option>#{shark}</option>"} print options Out put ["<option>Hammerhead</option>", "<option>Great White</option>", "<option>Tiger</option>", "<option>Whale</option>"] |
map
returns a new array, causing the original array to not be modified. Use map!
will modify the existing array. And remember that map
with alias are collect
. You should be consistent and use one or the other in your code.
8. Convert array into string
to_s
:
1 2 3 4 | sharks = ["Hammerhead", "Great White", "Tiger", "Whale"] Out put: “["Hammerhead", "Great White", "Tiger", "Whale"]" |
join
: can be combined with the condition to join the elements in the array into a “nice” string
1 2 3 4 5 6 7 8 9 10 11 12 13 | sharks = ["Hammerhead", "Great White", "Tiger", "Whale"] result = sharks.join(" ") print result Output Hammerhead Great White Tiger Whale sharks = ["Hammerhead", "Great White", "Tiger", "Whale"] result = sharks.join print result Output HammerheadGreat WhiteTigerWhale |
Using map
and join
is a quick way to convert a range of data. Use map when you want to convert some elements in the array, then use join
to join
them together. For example:
1 2 3 4 5 6 7 8 9 10 11 | sharks = ["Hammerhead", "Great White", "Tiger", "Whale"] options = sharks.map {|shark| "<option>#{shark}</option>"} output = options.join("n") print output Output <option>Hammerhead</option> <option>Great White</option> <option>Tiger</option> <option>Whale</option> |
9. Turn the array into a value
each
: When you work with a data set, you may find that you need to rearrange the data into a single value, such as a sum. One way you can do this is to use a variable and theeach
method:
1 2 3 4 5 6 7 | result = 0 [1, 2, 3].each {|num| result += num} print result Output 6 |
reduce
: You can use thereduce
method to do this.reduce
iterates over an array and keeps the total number of operations by performing a binary operation for each element.reduce
accepts an initial value for the result, as well as a block with two local values: a reference to the result and a reference to the current element. Inside the block, you specify the logic to calculate the final result. For example:
1 2 3 4 5 6 | output = [1,2,3].reduce(0) {|result, current| result += current } print output Output 6 |
If you intend to initialize the result to 0, you can omit the argument. For example:
1 2 3 4 5 6 | output = [1,2,3].reduce {|result, current| result += current } print output Output 6 |
reduce
is also that you specify a binary method or a method on an object that accepts another object as its argument, which will execute for each element in the array. reduce
then use the result to create a unique value.
1 2 | 2.+(2) # 4 |
Ruby uses some syntax so you can express it as 2 + 2.
reduce
allows you to specify a binary method by converting its name into a symbol. That means you can pass : +
to reduce
to sum the array:
1 2 3 4 5 6 | output = [1, 2, 3].reduce(:+) print output Output 6 |
You can use reduce
to do more than just adding a list of numbers. You can use it to convert values. Remember that reducing reduces an array to a value. But there is no rule that says the unique value could be another array.
Let’s say we have a list of values we need to convert into integers. but we only want the values to be converted to whole numbers.
We can use reject
to remove non-numeric values and then use map
to convert the remaining values into integers. But we can do it all in one step with reduce
.
Use an empty array as the initial value. Then, in the block, convert the current value to an Integer
using the Integer
method. If the value can be converted to an integer, Integer
will raise an exception, you can catch and assign nil
to the value.
Then take the value and put it into array, but only if it doesn’t nil
.
1 2 3 4 5 6 7 8 9 10 11 | values = ["1", "2", "a", "3"] integers = values.reduce([]) do |array, current| val = Integer(current) rescue nil array.push(val) unless val.nil? array end print integers Output [1,2,3] |
Conclude
In this tutorial, you used some methods to work with arrays. You took individual elements, retrieved values by searching in arrays, sorted elements, and you converted data, created new arrays, strings, and totals. You can apply these concepts to solve many common programming problems with Ruby.
Source of translation: https://www.digitalocean.com/community/tutorials/how-to-use-array-methods-in-ruby