Ruby is a dynamic, interpreted, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro “Matz” Matsumoto in Japan.

Ruby Basics

Data Types

```ruby
Type	Example
String	"Text"
Integer	10
Float	11.5
Range	(1..10) or ('a'..'z')
(1..10) includes 10
(1...10) exludes 10
Boolean	true (TrueClass)
false (FalseClass)
Array	list of elements [1, 2, 3]
["a", "b", "c"]
Hash	{ key: "value" }
Symbol	:symbol
```

Variables

  • We can store any datatype in a variable
  • This way we can re-use the value later
  • We can assign a value to the variable (store it in a box)
  • We can re-assign a value to the variable (open the box and store a new value)
```ruby
age = 29
name = "Sebastien"
array = [1, 2, 3]
hash = { key: "value" }
```

Concatenation

```ruby
first_name = "Boris"
last_name = "Paillard"
'I am' + ' ' + first_name + ' ' + last_name
You need to add the whitespace, otherwise it will turn into one big string
```

Interpolation

inject Ruby code inside a string delimiters must be double quotes

```ruby
"I am #{age} years old"
```

Incrementation/Decrementation

We can increment or decrement a variable that stores a number (Float or Integer)

```ruby
# Incrementation
age = age + 1
age += 1 # shortcut
# Decrementation
age = age - 1
age -= 1 # shortcut
```

Conditionals/Loops

Single branch conditional statement

```ruby
if age >= 18
  puts "You can vote"
end
# on a single line
puts "You can vote" if age >= 18
# using `unless`
unless age < 18
  puts "You can vote"
end
puts "You can vote" unless age < 18
```

Multi-branch conditional statement

```ruby
hour = Time.now.hour
if hour > 6
  puts "Good morning!"
elsif hour > 12 && hour < 18
  puts "Good afternoon!"
elsif hour > 18 && hour < 22
  puts "Good evening!"
else
  puts "Good night!"
end
```

Using case / when:

```ruby
puts "What do you want to do?"
action = gets.chomp

case action
when "read"
  puts "You are in READ mode"
when "write"
  puts "You are in WRITE mode"
when "exit"
  puts "Bye Bye"
else
  puts "Wrong action"
end
```

Loops

```ruby
while condition
  # executed while condition is truthy
end
until condition
  # executed until condition is truthy
end
loop do
  # run some code
  break if condition
end
# Not the idiomatic way to iterate through an array in Ruby
for num in [1, 2, 3]
  puts num
end
# Each is the idiomatic way to iterate through an array in Ruby
[1, 2, 3].each do |num|
  puts num
end
```

Methods

Methods are reusable blocks of code

Questions to ask yourself when writing a method:

Does it take parameters? If so: how many?

  • What’s the name of my method? Does it explain what it does?
  • What does the method return? It always returns something!
  • By default the last line of code
```ruby
def name_method(parameters)
  # method body
  # returns something
end
```

Parameters vs. Arguments

```ruby
# Method definition
def new_population(population, births)
  return population + births
end
# Method call
puts new_population(2000000, 300)
```
  • Argument: What we pass to the method when we call it
  • 2000000 and 300 are arguments
  • Parameter: placeholder for argument when we define the method
  • population and births are parameters

Array

  • list of elements
  • access by index
  • shortcut for an array of strings: %w(apple banana pear) will result in [“apple”, “banana”, “pear”]
    ```ruby
    # array of numbers
    [1, 2, 3, 4, 5]
    # array of strings
    ["seb", "boris", "edward"]
    # array of arrays
    [["valerie", 149], ["sarah", 111]]
    # can contain several datatypes (but not common)
    [1, "text", 13.5, true]
    ```
    

Hash

  • collection of key/value pairs
  • access a value with its key
  • keys and values can be of any data type
  • Examples
```ruby
# hash
teachers = { "valerie" => 149, "sarah" => 111 }
# more complex hash
paris = {
  "Paris" => {
    population: 2100000,
    monument: "Eiffel tower"
  }
}
```

CRUD: Array vs. Hash

```ruby
ACTION	ARRAY	                    HASH
create	array << element
        array.push(element)	      name_hash[key] = value
read	  array[index]	            name_hash[key]
update	array[index] = new value	name_hash[key] = new value
delete	array.delete(element)
        array.delete_at(index)	  name_hash.delete(key)
```

Useful built-in methods

  • String
```ruby
Object	Method	                  Explanation
String	.to_i	                    transforms the string into an Integer
String	.to_sym	                  transforms the string into a Symbol
String	.to_f	                    transforms the string into a Float
String	.split("")	              returns array of characters
String	.upcase
        .downcase
        .capitalize	              transforms the string
String	.gsub(regex, new_string)	replace something that matches regex
String	.scan(regex)	            scan a text for regex, returns array of matches
```
  • Integer/Float
```ruby
Object	Method	Explanation
Integer/Float	.to_s	transforms a Float or Integer to String
Integer/Float	.fdiv(num)	get exact division (with decimals)
Integer	.even?
        .odd?	check if an Integer is even or odd
Integer	rand(5)	get random number between e.g. 0..5
Float	.truncate
      .round	round Float up or down
```
  • Range
```ruby
Object Method	Explanation
Range	.to_a	  quickly get array of elements (1..5).to_a => [1, 2, 3, 4, 5]
```
  • Array
```ruby
Object	Method	Explanation
Array	.sort	# sort an array
Array	.sort_by # sort an array based on something
Array	.length
      .count
      .size	# returns how many elements in the array
Array	.each	# iterate over all the elements in the array
Array	.each_with_index # iterate over array with index
Array	.map # creates a new array
Array	.select
      .reject	# select or reject where condition is true
Array	.empty?	# check if array is empty
Array	.include?	# check if something is present in the array
Array	.join	# join elements in array to e.g. one big string
Array	.reverse	# reverse the array order of elements
Array	.sample	# get random element
Array	.shuffle	# randomize order of array
Array	.take(num)
      .drop(num)	# take or drop number (num) of elements of array
Array	.first
      .last	     select first or last element of array
```
  • Hash
```ruby
Object	Method	Explanation
Hash	.key?(name_key)	check if key exists in hash
Hash	.keys	get array of keys of the hash
Hash	.values	get array of hash values
Hash	.each do |key, value|	iterate over key and value of hash
```

Iterators & Block parameters

  • Iterators are methods we can call on collections such as an Array or a Hash
  • Comes with a block of code between do…end or between {…}
  • An iterator has block parameters, parameters we can pass to the block
```ruby
musicians = ['David Gilmour', 'Roger Waters', 'Richard Wright', 'Nick Mason']
musicians.each do |musician| # musician is the block parameter
  puts "Hello #{musician}!"
end
musicians.each_with_index do |musician, index| # musician & index are the block parameters
  puts "#{index + 1} - #{musician}"
end
```

Regex

We use Regular Expressions for data validation, e.g. to validate a form input and for data extraction, e.g. to extract phone numbers from a text. Regular Expressions have their own class, which comes with its own built-in methods

```ruby
Object	Method	Explanation
Regex	.match(regex_pattern)	returns a match_data object
Regex	.match?(string)	check if a regex matches a string
```

TO the past and future