An Interest In:
Web News this Week
- March 3, 2024
- March 2, 2024
- March 1, 2024
- February 29, 2024
- February 28, 2024
- February 27, 2024
- February 26, 2024
Arrays in Ruby
Welcome
Welcome, dear readers, coders, and enthusiasts!
Here we are with our next article. To be honest, the more I write (blog), the more I learn, repeat, and get more professional. As you all know, The best way to learn something is to teach it. So I try to write more about what I learn and what I do. And it gives me an opportunity to revise what I have learned and nail it deeper in my mind.
So, this time we are here to learn how to use and deal with Arrays in our beloved Ruby PL.
Arrays
An array is a data structure that is present in almost all programming languages. In short, Array is a collection of items that are placed in a certain order. You can store grades of students, product prices, product names and etc. in an Arrays. This is just an example. You can store more complex objects, data structures in an Array.
In Ruby PL, compared to some other programming languages, we can store various typed data in an Array. I.e. you can store Numeric, String, Boolean, and some other kind of complex objects. In regular programming languages, you can only store one type of object, like only String or only Number. The main point is to treat them in the given order. All items in an Array have an index number.
To summarize:
- Each of the elements in an array has an index number
- Indexing the elements starts with 0 (in an Array with n elements, the first element has index 0, and the last element has an index number n-1)
Creating a new Array
To create a new Array it is enough to place it in square brackets. For instance:
users = [] # Empty arrayusers = ["Arthur", "John", "Ford"] # 3 element Array# If the Array consists of only 'String' datausers = %w(Arthur, John, Ford)
There is another way to create an Array. It is by using the Array keyword.
numbers = Array.new # Empty array# Array with 3 nil elementsother_numbers = Array.new(3) # [nil, nil, nil]# Array with defined elementsthe_numbers = Array.new([15, 20, 25]) # [15, 20, 25]# Another Array with defined numbersfive_tens = Array.new(5, 10) # [10, 10, 10, 10, 10]
As you can see, you can create empty Arrays and Arrays with predefined elements. If you want, you can create an Array with a defined number of elements that are all equal to a certain value, as shown in the last example.
Accessing and updating elements
As we already have noted, all of the Array elements have an index number. What we always have to keep in mind is that the numbering starts with 0.
- in an array with 5 elements, the first element has an index 0, the last element has an index number 4;
- in an array with 10 elements, the first element has an index 0, the last element has an index number 9;
- in an array with m elements, first element has an index 0, the last element has an index number m-1;
To access array elements we use square brackets. If we want to get the element with an index number 3 in an array named grades, we access its element using grades[3].
seasons = ["Winter", "Sprint", "Summer", "Autumn"] # 4 elementsputs seasons[0] # The first element, with an indeks '0'puts seasons[3] # The last element, with an index '3'# Updating elementsseasons[0] = "Cold winter"seasons[2] = "Hot summer"
Besides using index numbers, Ruby has made it easier and gave us built-in first and last methods. As you already have understood, these methods get you elements with indices 0 and n-1.
cities = ["Boston", "Seoul", "Delhi", "Dubai"]puts cities.first # "Boston"puts cities.last # "Dubai"
Inserting and removing elements
We have two groups of commands to use when we want to insert and remove elements from an Array. One group methods insert and remove from the end of an Array. The other group methods insert and remove elements from the start of an Array.
Here they are:
- push (insert to the end of an Array)
- pop (remove from the end of an Array)
- -
- unshift (insert to the start of an Array)
- shift (remove from the start of an Array)
planets = ["Mars", "Earth"]# 'push' & 'pop' methodsplanets.push "Neptune" # ["Mars", "Earth", "Neptune"]planets.push "Saturn" # ["Mars", "Earth", "Neptune", "Saturn"]# Remove last element (pop)planets.pop # ["Mars", "Earth", "Neptune"]planets.pop # ["Mars", "Earth"]# 'unshift' & 'shift' methodsplanets.unshift "Neptune" # ["Neptune", "Mars", "Earth"]planets.unshift "Saturn" # ["Saturn", "Neptune", "Mars", "Earth"]planets.shift # ["Neptune", "Mars", "Earth"]planets.shift # ["Mars", "Earth"]# delete_atcolors = ["yellow", "white", "blue", "black"]colors.delete_at 2 # Remove element with index '2', that is 'blue'# ["yellow", "white, "black"]
Methods that insert new elements return a new state of the Array. Methods that remove an element from an Array, just return the removed element.
kids = ["Larry", "Brandon", "May", "John"]first_kid = kids.shift# first_kid => "Larry"# kids = ["Brandon", "May", "John"]last_kid = chagalar.pop# last_kid=> "John"# kids = ["Brandon", "May"]
An Array has another method to add elements to it. It is actually a short version of push method. You can use it with << symbols.
colors = ["yellow", "white"]colors<<"blue" # ["yellow", "white", "blue"]colors<<"black" # ["yellow", "white", "blue", "black"]
Size of an Array
Ruby PL has three methods to get the number of elements in an Array. It returns the size of the Array. Many programming languages use either of these methods. But developers of Ruby decided to include them all together. Here the are:
- length
- size
- count
- empty? (checks whether the Array is empty or not, returns true or false)
colors = ["yellow", "white", "blue", "black"]puts colors.length # 4puts colors.size # 4puts colors.count # 4puts colors.empty? # false
Iterating through Array elements
To iterate through Array elements we have two mostly used methods. They are each and each_with_index methods.
- each (iterates through Array elements)
- each_with_index (additionally, gives access to element index)
colors = ["yellow", "white", "blue", "black", "red"]colors.each { |element| puts element } # yellow# white# blue# black# redcolors.each_with_index { |elem, index| puts "#{index} - #{elem}" } # 0 - yellow# 1 - white# 2 - blue# 3 - black# 4 - red
Extra methods
- sort (Ordering): Used to order Array elements.
- uniq (non-repeating elements): returns only non-repeating, unique elements of the Array.
numbers = [1, 7, 2, 3, 3, 6, 5, 5]puts numbers.sort # [1, 2, 3, 3, 5, 5, 6, 7]numbers = numbers.uniq# => [1, 2, 3, 5, 6, 7]
- join: joins Array elements into a single String.
- split: splits String type element into Array elements.
letters = %w(a b c d)puts letters.join # "abcd"puts "a b c".split # ["a", "b", "c"]
Conclusion
Dear readers. Here we come to the end of the article about Ruby Arrays. Array methods are not only restricted to the ones listed here, in the article. We could have counted and written many more of them. No need to load the learner with loads at once. So if you want a bit more, just go to the documentation where you can find much more about Ruby and Arrays.
So, this is all for now. Stay hungry, stay healthy guys!
Original Link: https://dev.to/eminarium/arrays-in-ruby-1kp8
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To