Ruby Tutorial Part 01 Arrays, Ranges And Hashes

in utopian-io •  6 years ago 

Repository

https://github.com/ruby/ruby 

What Will I Learn?

  • You will learn the arrays.
  • You will learn the ranges.
  • You will learn the hashes.

Requirements

  • You need to have Ruby installed on your computer

Difficulty

  • Basic

Tutorial Contents

Ruby is an interpreted, high-level, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan.Ruby is dynamically typed and garbage-collected. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming. 

In this tutorial we will learn 3 points in Ruby " The Arrays, Ranges and Hashes ".

1- Arrays

Imagine for example, that you write a program about your class at school, it contains all the names of students in your class and assuming they are 30 people, do you imagine the creation of 30 variables ?

The solution is the array, which is a structure of information used to store a set of variables linked to each other without creating variables to include the values of each one.

a- Creation of the array

First, to create an object for the array there are more than one method

1- Using the method of " new " from the " Array Class " and it return an object from " Array Class ".

arr = Array.new // create object from Array

#output => []

The " output " means what ruby returns when we execute the code.

2- Direct reference

arr = [ ] #create an array directly

#output => []

We return again to the " New " method, which has some properties for example " populating " which is the addition of values once the object is created.

arr = Array.new(4) #4 nils!

#output => [nil, nil, nil, nil]

Here we said to the " new " method that we want to create an object from the array, and it has 4 elements but we did not define the values of the elements, it took "nil" by default.

arr = Array.new(4){"test"} #array contains 4 elements all are test 

#output => ["test", "test", "test", "test"]

Here we said to the " new " method that we want an object from the array, and it has 4 elements and the value of each one is " test ".

The best solution is to put the names of the students in the array, the first element in the array indexed by 0.

students = ["Alex", "Christina", "Rogina", "Sordin",...] # an array of students

#output => ["Alex", "Christina", "Rogina", "Sordin",...] 

If for example, I want to print an element from the array or several elements, how can I do that?

puts students[0]  # print the first element

#output =>  Alex 

puts students[0..3] # print the 4 first elements 

#output =>  Alex Christina Rogina Sordin

puts students[-1] # print the first element from the bottom

#output => Sordin

b- Array Functions

1- Include?(obj) Function

Is a "function" within the array class and returns a true or false value, simply it tells us if the array contains the object passed as parameter or not.

puts "Alex included!" if students.include?("Alex") 

#output => Alex included!

2- Length and Size Functions

The "length" or "size" functions return the number of elements in the array, where we often need to return the number of elements in the array to use it in a " loop" or anything.

puts students.length 

#output => 5

puts students.size 

#output => 5

3- Delete_at(index) Function

This function will delete the element that has the index passed as parameter, and if the index is negative or incorrect the function will return false value.

students.delete_at(3) #Sordin is removed. 

4- Clear Function

The clear function used to delete all elements in the array.

students.clear #delete all 

p students 

#output => 0

5- Empty? Function

The empty? method returns a boolean value to check if the array is empty or not ( true or false ).

students.clear puts "Array is empty" 

if students.empty? 

#output => Array is empty

6- Insert(index, object) Function

The insert method used to add an element to the array by the index, it has the " index and object" as parameters.

students = ["Alex", "Christina", "Rogina", "Sordin"] 

students.insert(4, "Oscar") 

p students 

#output => ["Alex", "Christina", "Rogina", "Sordin", "Oscar"]

7- Concat(array) Function 

We have seen how to add a single element to the array, now we will see how we can add another array to the current array using this method.

students = ["Alex", "Christina", "Rogina", "Sordin", "Oscar"]

students.concat(["Noah", "Charlie"])

p students 

#output => ["Alex", "Christina", "Rogina", "Sordin", "Oscar","Noah", "Charlie"]

8- Last and First Functions

At place of using the indexes students[index] to get an element, Ruby provides us a very efficient functions to get the first and the last elements from our array.

puts students.last

#output => Charlie

And if you want to get the two last elements you can pass " 2 " as parameter to the last function

puts students.last(2)

#output => Noah Charlie

The same thing if we want to get the first element of the array

puts students.first

#output => Alex

And if you want to get the two first elements you can pass " 2 " as parameter to the first function

puts students.first(2)

#output => Alex Christina

9- Replace Function

This method is used to replace all array elements with other array elements

langs = ["Pascal", "C", "Perl"] 

langs.replace(["Ruby", "Python", "C#", "Java"]) 

p langs 

#output => ["Ruby", "Python", "C#", "Java"]

10- Reverse Function

This method is used to return a copy of the array but in reverse order

reversedLangs = langs.reverse 

p langs 

#output => ["Ruby", "Python", "C#", "Java"]

p reversedLangs 

#output =>  ["Java", "C#", "Python", "Ruby"]

If you look, you can see that the reverse was not worked with the original array, but on the assumption that we want the change to occur on the original array, the solution is to use " !reverse " function.

Every function you find the exclamation point "!" means it's a destructive function and that means also that the effect will be on the object itself and not on its copy. Here in our example, the elements reflected in the object itself and not a copy of it

langs=["Pascal", "C", "Perl"] 

langs.reverse! 

p langs 

#output: ["Perl", "C", "Pascal"

11- Uniq and !uniq Functions

The uniq method or function returns a copy of the array of elements but without repeating, and the !uniq function deletes all duplicates of items and makes it appear only once.

ary = [1, 2, 3 ,3, 5, 6, 7, 7, 7, 10] 

p ary 

uniqAry = ary.uniq 

p ary 

p uniqAry 

ary.uniq! 

p ary 

#output => [1, 2, 3, 3, 5, 6, 7, 7, 7, 10] 

[1, 2, 3, 3, 5, 6, 7, 7, 7, 10] 

[1, 2, 3, 5, 6, 7, 10] 

[1, 2, 3, 5, 6, 7, 10]

12- Sort Function

It is a method that reproduces a copy of the array but is arranged, but if you want the adjustment to be always on the array use !sort function.

ary = [1, 2, 5,623, 14, 512] 

p ary.sort 

#output => [1, 2, 5, 14, 512, 623] 

ary.sort! #destructive 

p ary 

#output => [1, 2, 5, 14, 512, 623]

Look at this code we will add and remove items with many ways 

old= ["C", "Pascal", "Fortran"] 

new = ["Python", "Ruby", "Java"] 

all = old + new #or all = old.concat(new) 

p all 

#output => ["C", "Pascal", "Fortran", "Python", "Ruby", "Java"] 

all << "C#" # or we can use 'add c#'. 

p all 

#output => ["C", "Pascal", "Fortran", "Python", "Ruby", "Java", "C#"] 

all.push("Perl") # << perl 

p all 

#output => ["C", "Pascal", "Fortran", "Python", "Ruby", "Java", "C#", "Perl"] 

all.pop # remove the last element. 

p all 

#output => ["C", "Pascal", "Fortran", "Python", "Ruby", "Java", "C#"] 

Now we have two arrays, we will use the " Union, minus and intersection "

langs = ["C", "Python", "Ruby", "Pascal"] 

intrep_langs = ["Python", "Ruby", "Groovy"]

#union 

un = langs|intrep_langs 

p un 

#output =>  ["C", "Python", "Ruby", "Pascal", "Groovy"]

#difference 

diff = langs-intrep_langs 

p diff 

#output => ["C", "Pascal"]

#intersection 

intSec = langs & intrep_langs 

p intSec 

#output => ["Python", "Ruby"]

To use the union of two array we can use the "|" , where we put it between two arrays and print the result, also to use the difference we will use the "-", and finally to use the intersection we use the "&".

2- Ranges

Range is a period consisting of " Start, Step and End ".

rng1to10 = 1..10  #10 is included 

p rng1to10.to_a  #to_a means to array 

#output => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

rng1to9 = 1...10 #10 isn't included 

p rng1to9.to_a 

#output => [1, 2, 3, 4, 5, 6, 7, 8, 9]

Min

It is a method that returns the smallest elements of range

Max

It is a method that returns the largest elements of the range

rng=1..10 

p rng.to_a 

puts rng.min #min 

#output 1 

puts rng.max #max 

#output 10

The use of the ranges is often used in the formation of arrays that contain many elements, for example from 1 to 100 or from a to z

alphabet=('a'..'z').to_a 

p alphabet 

#output ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] 

words = ('abc'..'abk').to_a 

p words 

["abc", "abd", "abe", "abf", "abg", "abh", "abi", "abj", "abk"]

3- Hashes

It is a very famous data structure in many languages and can be encountered before under another name such as the dictionary in Python or Associative array in Perl.

a- What's the Hash ?

It's a dictionary in the sense that you define the key and the value.

b- Creation of Hash

First, to create a Hash table we need to use the " new " way from the Hash Class

hashTable = Hash.new #Create a new Hash object. 

or

hasTable = { }

Let's create an example to understand what's the difference between Hash and Array

hashTable["name"] = "Alex" 

hashTable["age"] = 18 

hashTable["sex"] = 'm' 

p hashTable

#output => {"name"=>"Alex", "sex"=>"m", "age"=>18}

c- Hash functions

1-Store(key,value) Function

To add elements to the Hash we can use the store method, we pass the key as " name " for example and the value for this key.

hash.store("lang", "ruby") #Adding key, value by using store method. 

#output => {"name"=>"Alex", "lang"=>"ruby", "sex"=>"m", "age"=>18}

We can simply get a value through the key using the Index or Fetch method

hashTable[key] #returns the value 

hashTable.fetch(key) #returns the value

hash={"name"=>"Alex", "sex"=>"m", "age"=>18} 

puts "Name: " << hash["name"] 

#output => Name: Alex

puts "sex : " << hash.fetch("sex") 

#output =>  sex : m

2- Shift Function

 This function returns an array contains two elements or more, this array will be divided, the first element is the key and the second element is the value

hash={"name"=>"Alex", "sex"=>"m", "age"=>18} 

ary = hash.shift 

p ary 

#output => ["name", "Alex"]

3- Invert Method

This function converts the values of the Hash to keys and the keys to values, sometimes it works with two functions " has_key and has_value ", all of these functions return a boolean value ( True/False )

hash = {"name"=>"Alex", "sex"=>"m", "age"=>18} 

invHash = hash.invert 

p invHash 

#output => {"m"=>"sex", 18=>"age", "Alex"=>"name"} 

puts invHash["Alex"] 

#output => name

4- Length Function

This function returns the number of pairs" key/value " in the Hash

hash={"name"=>"Alex", "sex"=>"m", "age"=>18} 

puts hash.length #number of pairs 

#output => 3

5- To_a Function

This function convert the Hash to an array, or let's say convert each element of Hash to an array and put them in the same array

hash={"name"=>"Alex", "sex"=>"m", "age"=>18}

ary = hash.to_a #convert to array 

p ary 

#output => [["name", "Alex"], ["sex", "m"], ["age", 18]]

6- Hash Function

To convert from array to hash we must use the function " Hash ", it will combine between each two elements and form a Hash.

ary = ["first", 1, "second", 2, "third", 3] 

hash = Hash[*ary] 

p hash 

#output => {"second"=>2, "first"=>1, "third"=>3}

7- Keys and Values Functions

To return just the keys from the Hash or just the values we will select the name of Hash and chose the keys or values.

hash = {"name"=>"Alex", "sex"=>"m", "age"=>18} 

keys = hash.keys 

p keys 

#output => ["name", "sex", "age"] 

vals = hash.values 

p vals 

#output => ["Alex", "m", 18]

Thanks for your reading.

Curriculum

The First tutorial.

Proof of Work Done

 https://github.com/alex-harry/rubyTutorial/blob/master/ruby.rb 

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  
Loading...

Hi @alex-harry!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @alex-harry!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Congratulations @alex-harry!
Your post was mentioned in the Steem Hit Parade for newcomers in the following category:

  • Pending payout - Ranked 5 with $ 4,85

I also upvoted your post to increase its reward
If you like my work to promote newcomers and give them more visibility on the Steem blockchain, consider to vote for my witness!

Congratulations @alex-harry! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You received more than 50 upvotes. Your next target is to reach 100 upvotes.

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Vote for @Steemitboard as a witness to get one more award and increased upvotes!