Coding Ruby

Use Array Methods in Ruby

ruby-logo

Use Array Methods in Ruby

Introduction:

  • Arrays represent lists of information in your programs.
  • Once you have got information in associate degree array, you’ll find it, take away duplicates, reverse its order, extract sections of the array, or search through arrays for specific information.
  • You also can convert associate degree array to a string, remodel one array of information into another, associate degreed roll up an array into one price.
  • You’ll explore a number of the foremost sensible ways Ruby offer for operating with information keep in arrays.
  • As you’re employed through this tutorial, you will see some ways that finish with associate degree punctuation (!). These ways typically have side-effects, like mutating the initial price or raising exceptions. several ways you may use during this tutorial have a connected methodology with this suffix.
  • You’ll additionally stumble upon ways that finish with a matter mark (?). These ways come to a mathematician price.
  • These are the naming convention used throughout Ruby. it isn’t one thing that is enforced at the program level; it’s simply differently to spot what you’ll expect from the tactic.
  • Start our exploration of array methods in Ruby by observing many ways that to access components

Different array methods in Ruby:

Accessing components

  • If you have already followed the tutorial the way to Work with Arrays in Ruby, you recognize you’ll access a personal part victimization its index, that is zero-based, like this:
sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sharks[0]    # "Tiger"
sharks[1]    # "Great White"
sharks[-1]   # "Angel"
  • You additionally would possibly recall that you just will use the primary associate degreed last ways to grab the primary and last components of an array:
sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sharks.first   # "Tiger"
sharks.last    # "Angel"
  • Finally, once you access a component that does not exist, you may get a cipher. However, if you want to induce a blunder instead, use the fetch method:
sharks.fetch(42)

Output:

IndexError: index 42 outside of array bounds: -4...4
  • If you’d rather specify your own default rather than raising a blunder, you’ll try this too:
sharks.fetch(42, "Nope")     # "Nope"
  • Now let’s examine the way to get over one part from associate degree array.

Retrieving Multiple components

  • There are times you may wish to grab a set of values from your array rather than simply one part.
  • If you specify a beginning index, followed by the number of components you would like, you will get a replacement array containing those values. For instance, you’ll grab the 2 middle entries from the sharks array like this:
sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sharks[1,2]   # ["Great White", "Hammerhead"] 
  • We begin at index one, that is “Great White“, and that we specify we would like two components, thus we tend to get a replacement array containing “Great White” and “Hammerhead“.
  • You will use the slice methodology to try and do the constant thing:
sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sharks.slice(1,2)   # ["Great White", "Hammerhead"] 
  • The slice methodology additionally returns a replacement array, effort the initial array unchanged. However, if you utilize the slice! methodology, the initial array are going to be modified yet.
  • The take methodology permits you to grab the required range of entries from the start of associate degree array:
sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sharks.take(2)  # ["Tiger", "Great White"]
  • Sometimes you would like to grab a random price from associate degree array rather than a particular one. Let’s explore, however.

Getting a Random Entry from associate degree Array

  • You can be performing on a game of probability, or even you are writing a program that picks a contest winner. Those styles of things need some reasonably random price. A typical answer is to place the alternatives in associate degree array and choose a random index.
  • To get a random part from associate degree array, you’ll generate a random index between zero and also the last index of the array associate degreed use that as an index to retrieve the worth, however, there is a better way: the sample methodology grabs a random entry from associate degree array.
  • Let’s use it to grab a random associate degree were from an array of stock answers, making a primitive version of a Magic 8-Ball game:
answers = ["Yes", "No", "Maybe", "Ask again later"]
print answers.sample

Output:

Maybe
  • The sample methodology additionally accepts associate degree argument that returns associate degree array of random entries, thus if you happen to wish over one random entry, simply provide the quantity you’d like:
random_sharks.rb
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
sample = sharks.sample(2)
print sample

Output:

["Whale", "Great White"]
  • Let’s examine the way to notice specific components in associate degree array next.
READ  Whatsapp for Android gets Document Sharing Feature

Finding and Filtering components

  • When you are looking for specific components in associate degree array, you usually repeat over its components till you discover what you are looking for. However, Ruby arrays offer many ways specifically designed to alter the method of rummaging through arrays.
  • If you only wish to envision if a component exists, you’ll use the include? methodology, that returns true if the required information is a component of the array:
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
sharks.include? "Tiger"      # true

["a", "b", "c"].include? 2   # false
  • However, include? needs an explicit match, thus you cannot hunt for a partial word.
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
sharks.include? "Tiger"      # true
sharks.include? "tiger"      # false
sharks.include? "ti"         # false
  • The notice methodology locates and returns the primary part within the array that matches a condition you specify.
  • For example, to spot the primary entry within the sharks array that contains the letter a, you’ll use every methodology to check every entry and stop iterating once you notice the primary one, like this:
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
result = nil
sharks.each do |shark|
  if sharks.include? "a"
    result = shark
    break
  end
end
  • Or you’ll use the notice methodology to try and do the constant thing:
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
result = sharks.find {|item| item.include?("a")}
print result

Output:

Hammerhead
  • find executes the block you offer for every part within the array. If the last expression within the block evaluates to true, the notice methodology returns the worth and stops iterating. If it does not notice something once iterating through all of the weather, it returns nil.
  • The chosen methodology works in a similar manner, however, it constructs a replacement array containing all of the weather that match the condition, rather than simply returning one price and stopping.
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
results = sharks.select {|item| item.include?("a")}
print results

Output:

["Hammerhead", "Great White", "Whale"]
  • The reject methodology returns a replacement array containing components that do not match the condition. you’ll consider it as a filter that removes components you do not wish. Here’s associate degree example that rejects all entries that contain the letter a:
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
results = sharks.reject {|item| item.include?("a")}
print results

Output:

["Tiger"]
  • select and reject each come to a replacement array, effort the initial array unchanged. However, if you utilize the select! and reject! ways, the initial array is going to be changed.
  • The find_all methodology is associate degree alias for choose, however, there’s no find_all! methodology.
  • Next, let’s examine the way to kind the values of associate degree array.

Sorting associate degree Array

  • Sorting information may be a common follow. You will have to be compelled to alphabetize an inventory of names or kind numbers from smallest to largest.
  • Ruby arrays have a reverse methodology which may reverse the order of the weather in associate degree array.
  • If you have got an inventory of information that is already organized, the reverse may be a fast thanks to flip the weather around:
sharks = ["Angel", "Great White", "Hammerhead", "Tiger"]
reversed_sharks = sharks.reverse
print reversed_sharks

Output:

["Tiger", "Hammerhead", "Great White", "Angel"]
  • The reverse methodology returns a replacement array and does not modify the initial. Use the reverse! methodology if you would like to alter the initial array instead.
  • However, reversing associate degree array is not the foremost efficient, or sensible, thanks to kind information. Use the kind methodology to sort the weather in associate degree array the manner you want.
  • For straightforward arrays of strings or numbers, the kind methodology is economical and can offer you the results you are looking for:
sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sorted_sharks = sharks.sort
print sorted_sharks

Output:

["Angel", "Great White", "Hammerhead", "Tiger"]
  • However, if you needed to kind things a special manner, you’ll be wanting to inform the kind methodology the way to try this. This methodology takes a Ruby block that provides you access to components within the array so you’ll compare them.
  • To do the comparison, you utilize the comparison operator (), typically named because of the ballistic capsule operator. This operator compares 2 Ruby objects and returns -1 if the thing on the left is smaller, zero if the objects are constant, and one if the thing on the left is greater.
1 <=> 2    # -1
2 <=> 2    #  0
2 <=> 1    #  1
  • Sort methodology accepts a block that has to come -1, 0, or 1, that it then uses to kind the values within the array.
  • Here’s associate degree example that expressly compares the entries within the array to kind in ascending order:
sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sorted_sharks = sharks.sort{|a,b| a <=> b }
print sorted_sharks
  • The a and b variables represent individual components within the array that are compared. The result appears like this:
READ  C Programming - Check divisibility by 7

Output:

["Angel", "Great White", "Hammerhead", "Tiger"]
  • To kind the sharks within the reverse order, reverse the objects within the comparison:
sharks = ["Tiger", "Great White", "Hammerhead", "Angel"]
sorted_sharks = sharks.sort{|a,b| b <=> a }
print sorted_sharks

Output:

["Tiger", "Hammerhead", "Great White", "Angel"]
  • The kind methodology is nice for arrays containing straightforward information sorts like integers, floats, and strings. However, once arrays contain additional complicated objects, you will have to try and do a touch additional work.
  • Here’s associate degree array of hashes, with every hash representing a shark:
sharks = [
  {name: "Hammerhead"},
  {name: "Great white"},
  {name: "Angel"}
]
  • Sorting this with kind is not as straightforward. occupation kind on the array fails:
sharks.sort

Output:

ArgumentError: comparison of Hash with Hash failed
  • In order to try and do the comparison, we’ve to sort what we would like to check. thus we’ll compare the values of the :name key within the hash:
sorted_sharks.sort{|a, b| a[:name] <=> b[:name]}
print sorted_sharks

Output:

[{:name=>"Angel"}, {:name=>"Great white"}, {:name=>"Hammerhead"}]
  • When you are operating with additional complicated structures, you may wish to seem at the sort_by methodology instead, that uses an additional economical formula for sorting. sort_by takes a block that sorely needs one argument, the respect to this part within the array:
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"}]
  • The sort_by methodology implements a Schwartzian remodel, an algorithm best fitted to comparison objects supported the worth of a particular key. Therefore, you will find yourself victimization sort_by whenever comparison collections of objects, as it’s additional economical.
  • Both kind and sort_by come new arrays, effort the initial array intact. If you would like to switch the initial array, use sort! and sort_by! instead.
  • In addition to sorting values, you may additionally wish to induce obviate duplicates.

Removing Duplicate components

  • Sometimes you will get lists of information that have some duplication. you’ll repeat through the array and separate out the duplicates. However, Ruby’s uniq methodology makes that loads easier. The uniq methodology returns a replacement array with all duplicate values removed.
[1,2,3,4,1,5,3].uniq   # [1,2,3,4,5]
  • Sometimes, once you merge 2 sets of information, you may find yourself with duplicates. Take these 2 arrays of sharks:
sharks = ["Tiger", "Great White"]
new_sharks = ["Tiger", "Hammerhead"]
  • If we tend to add them along, we’ll get a reproduction entry:
sharks + new_sharks
# ["Tiger", "Great White", "Tiger", "Hammerhead"]
  • You might use uniq to get rid of the duplicates, however, it’s higher to avoid introducing them entirely. Rather than adding the arrays along, use the pipe operator |, that merges the arrays together:
sharks | new_sharks
# ["Tiger", "Great White", "Hammerhead"]
  • Ruby arrays additionally support subtraction, which implies you’ll deduct new_sharks from sharks to induce solely the new values:
sharks = ["Tiger", "Great White"]
new_sharks = ["Tiger", "Hammerhead"]
sharks - new_sharks   # ["Great White"]
  • Next, let’s examine the way to manipulate every element’s price.

Transforming information

  • The map methodology and its alias collect will remodel the contents of the array, that means that it will perform associate degree operation on every part within the array.
  • For example, you’ll use map to perform arithmetic on every entry in associate degree array, and make a replacement array containing the new values:
numbers = [2,4,6,8]

# square each number
squared_numbers = numbers.map {|number| number * number}

print squared_numbers
  • The squared_numbers variable is associate degree array of the initial numbers, squared:
  • [4, 16, 36, 64]
  • map is commonly employed in internet applications to rework associate degree array into components for associate degree markup language dropdown list. Here’s a really simplified version of however that may look:
]sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]

options = sharks.map {|shark| "<option>#{shark}</option>"}

print options
  • Without modifying the original array, the map gives a new array form. map! helps to modify the present array. the map also is known as collect. Use any one of the codes.
  • Meanwhile, map returns a new array, the array can then be changed and operated or even transformed to a string.
READ  Java Programming - Egg Dropping Puzzle

Convert an Array to a String

  • To convert an object to a string, Ruby has a to_s method. It is used in print statement. An array of sharks is given below.
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]

to_s method created this string format

"[\"Hammerhead\", \"Great White\", \"Tiger\", \"Whale\"]"

Not used in the real program but helpful in debugging.

  • To convert an array to a string, join method is used. It gives controls to combine elements. In this method, the argument is taken which agrees with the character as the separator. Let us change the sharks array as strings that are separated using spaces:
shark_join.rb
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
result = sharks.join(" ")
print result

Output:

Hammerhead Great White Tiger Whale

Using comma and space as a delimiter, the names can be separated

shark_join.rb
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
result = sharks.join(", ")
print result

Output:

Hammerhead, Great White, Tiger, Whale
  • In a map, to alter an array of information as output, we use the join method. First, we transform every content in the information using map function, then we transform all the content into the string which we print.
  • Sample example, here join is used to convert an array into the string with the help of newline character as the separator.
map.rb
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>

If you need to do different transformation which gives single value by using the total of contents, instead of converting an array into a string format.

Reduce Arrays as Single Value

Using a variable and each method, the set of data can be rulled up into a single value.

result = 0
[1, 2, 3].each {|num| result += num}
print result

Output:

6
  • reduce method can be used, because it iterates array and executes the binary operation for every element and keeps running total.
  • It accepts the initial value for a result, block with 2 local values that is a reference for a result and a reference to the present element. We give logic inside of block to compute a result.
  • First, initialize the result as 0 and add present value to result which is present in the block, so that we can sum up the array.
output = [1,2,3].reduce(0) {|result, current| result += current }
print output

Output:

6

In reduce method, we can give binary method or 1 object agrees with other objects as the argument is another method that executes every pass in an array. It uses the result to create a single value.

While we write 2+2, the + method is invoked on integer 2

2+(2) # 4

Syntactic sugar method is used to express 2+2 simply.

By using this method, a binary method can be specified by passing the name as a symbol which means :+ to reduce method to get the sum of an array.

output = [1, 2, 3].reduce(:+)   
print output

Output:

6

reduce method is used to perform more operations such as add list of numbers, transform values, reduce array into the single value.

For non-numeric values, reject method is used. And the map is used to alter other remaining values into integer format. But reduce method will do it in 1 step.

For initialization take the empty array. With the help of the integer method, the present value is transformed into an integer. If it is not changed into an integer, the exception is raised. So that you catch and assign its value as nil.

But only if it’s not nil, take the value and put it in the array.

Try this code:

convert_array_of_values.rb
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]

Conclusion:

In this tutorial, we learned to use some array methods in Ruby. Individual elements are grabbed and retrieved values by searching in the array, sorted and transformed the information or data, created arrays, string and total. These same concepts can be applied to solve more common problems in the Ruby language.

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment