Ruby Le Wagon Flashcards
Commenting in Ruby?
#
Two Types of Numeric Numbers in Ruby?
Integer for whole numbers
Float for decimal numbers
How to determine the type of data in Ruby?
.class
name = “Dimitri”
puts name.class # => will return String
Checking for odd or even in Ruby?
10.even? # => will return true
22.odd? # => will return false
Changing an object in a string in Ruby?
.to_s
How to get an integer from a float in Ruby?
.round
Upper Case, capitalizing, reversing in Ruby?
.upcase, .capitalize, .reverse
How to sort arrays in Ruby?
with .sort and .reverse
my_array = [1, 3, 2, 6]
my_array.sort … [1, 2, 3, 6]
my_array.sort.reverse … [6, 3, 2, 1]
Converting Strings to Numbers in Ruby?
to_i –> string to interger
to_f –> string to float
e.g.
“5”.to_i —> 5
Shorthand in Ruby for converting a method into a block
&:
It gets passed to methods like ‘map’ or ‘select’ for concise code.
e.g.
string.map(&:to_i) –> iterates over an string and converts it into numbers(if htere are nums)
Converting Numbers to String in Ruby?
With the ‘to_s’ method.
e.g.:
number = 42
string_number = number.to_s
puts string_number # Output: “42”
How to get the highest and/or lowest numbers of an array in Ruby?
.min
.max
.minmax –> array of the highest and lowest number
How does the fetch method work?
.fetch(key, default value)
If the key exists in the dictionary, fetch returns the corresponding value.
If the key does not exist, fetch returns the default value e.g. (0).
This effectively ensures that even if the key is not found in the dictionary, the expression will not raise an error, but instead return 0.
Bash command for the filepath of the current directory?
pwd (print working directory)
Bash command that lists files and directories in current directory?
ls
Bash command that navigates from one folder to another?
cd path/to/go
Bash command that creates a new directory?
mkdir folder_name
Bash command that creates a new file?
touch file_name
Bash command that moves the file into the directory?
mv file_name path/to/directory?
Bash command that removes a file?
rm path/to/file
Bash command that display the content of a file?
cat file_name
In Ruby, how to use the scan method to extract substrings from a string based on a specified pattern and return an array of matches?
.scan(>pattern<)
How to delimit a regular expression pattern in Ruby?
With two forward dashes:
/…/
What are character classes in Ruby?
A character class in regular expressions is a set of characters enclosed within square brackets […]. It allows you to specify a group of characters that you want to match at a particular position in the string. For example:
[abc] matches any one of the characters ‘a’, ‘b’, or ‘c’.
[a-z] matches any lowercase letter from ‘a’ to ‘z’.
[0-9] matches any digit from ‘0’ to ‘9’.
[-] matches either an underscore ‘’ or a hyphen ‘-‘.
How can you concatenate the items of an array in Ruby?
.join(“…”)
… = the characters between the items
What are the exclusive and inclusiv operators in Ruby?
… is exclusiv (0…3»_space; 0, 1, 2)
.. is inclusive (0..3)» 0, 1, 2, 3)
How to split a String sentence into an Array of words in Ruby?
“string”.split(“ “)
Do you know a shortcut to define an array of strings in Ruby?
There are three ways you can define an array of strings without typing quotes
%w[Huey Dewey Louie] #=> [“Huey”, “Dewey”, “Louie”]
What is the main difference between single quotes ‘ and double quotes “ in Ruby?
You can only interpolate between double quotes:
“two: #{1 + 1}”
How can you get the position (index) of an item in an array in Ruby?
You can call .index on the array, passing it the item you look for as an argument
beatles = [“John”, “Ringo”, “Paul”, “George”]
beatles.index(“John”) #=> 0
Warning: if the array has several occurrences of the item, this will return only the index of the first one.
Do you know the best way to iterate through the items of an array in Ruby?
[1, 2, 3].each do |num|
puts num
end
[1, 2, 3].each { |num| puts num }
How can you delete an item from an array in Ruby?
.delete:
beatles = [“John”, “Ringo”, “Paul”, “George”]
beatles.delete(“John”)
beatles #=> [“Ringo”, “Paul”, “George”]
You can also call .delete_at on the array, passing it the index of item you want to delete as an argument:
beatles = [“John”, “Ringo”, “Paul”, “George”]
beatles.delete_at(0)
beatles #=> [“Ringo”, “Paul”, “George”]
What is the opposite of while in Ruby?
until:
until condition
# loops while condition
is falsy
end
How can you test if an item is included in an array in Ruby?
.include?
beatles = [“John”, “Ringo”, “Paul”, “George”]
beatles.include?(“John”) #=> true
beatles.include?(“Boris”) #=> false
Is there a way to have the index and the element when you iterate through an Array in Ruby?
You can use #each_with_index
musicians = [“Jimmy Page”, “Robert Plant”, “John Paul Jones”, “John Bonham”]
musicians.each_with_index do |musician, index|
puts “#{index + 1} - #{musician}”
end
1 - Jimmy Page
# 2 - Robert Plant
# 3 - John Paul Jones
# 4 - John Bonham
Which iterator should you call on an Array to get another Array where all the elements were subject to the same treatment in Ruby?
musicians = [“Jimmy Page”, “Robert Plant”, “John Paul Jones”, “John Bonham”]
musicians.map do |musician|
musician.upcase
end
=> [“JIMMY PAGE”, “ROBERT PLANT”, “JOHN PAUL JONES”, “JOHN BONHAM”]
How can you group Array items by pair or more in Ruby?
.each_slice(no. of items).to_a
How do you remove items matching a condition from an Array in Ruby?
.reject
musicians = [“Jimmy Page”, “Robert Plant”, “John Paul Jones”, “John Bonham”]
musicians.reject do |musician|
musician.start_with?(“J”) # reject only the elements that start with a “J”
end
=> [“Robert Plant”]
How would you sort an Array with a given sorting criteria in Ruby?
.sort_by
[“apple”, “pear”, “fig”].sort_by { |word| word.length }
#=> [“fig”, “pear”, “apple”]
How would you find the first element of an Array that satisfies a given condition in Ruby?
.find
musicians = [“Jimmy Page”, “Robert Plant”, “John Paul Jones”, “John Bonham”]
musicians.find { |musician| musician.split(“ “).first == “John” }
# => “John Paul Jones”
How do you count the number of Array elements matching a condition in Ruby?
.count
musicians = [“Jimmy Page”, “Robert Plant”, “John Paul Jones”, “John Bonham”]
musicians.count { |musician| musician.include? “J” }
=> 3
How can you tell if a key is present in a Hash?
hash.key? :key
boris = {
first_name: “Boris”,
github_nickname: “Papillard”
}
boris.key? :first_name
# => true
boris.key? :email
# => false
What method should you use on a Hash if you just need to iterate over its keys?
.each_key
boris.each_key do |key|
puts “Boris has a #{key}”
end
How can you get all the values of a Hash in an array?
.values
boris = {
first_name: “Boris”,
github_nickname: “Papillard”
}
boris.values
# => [“Boris”, “Papillard”]
When should you use a Symbol to store text, and when should you use a String?
You should use a Symbol when the text is a keyword with an internal purpose in your code, e.g. for identifiers.
You should use a String when the text is data, for instance user input, that you don’t control.
What iterator should you use on a Hash if you just need to operate on its values?
.each_value
boris.each_value do |value|
puts “#{value} is an attribute of boris”
end
How can you retrieve all the keys of a Hash into an array?
.keys
boris = {
first_name: “Boris”,
github_nickname: “Papillard”
}
boris.keys
# => [:first_name, :github_nickname]
How can you tell if a value is present in a Hash?
.value?
boris = {
first_name: “Boris”,
github_nickname: “Papillard”
}
boris.value?(“Boris”)
# => true
What is a Symbol?
A Symbol is a built-in Ruby object used to represent text.
It is characterized by its : prefix, e.g. :city
How can you iterate through a Hash?
ith .each (same as arrays) yet with two parameters key and value between the pipes:
city = { “name” => “Paris”, “population” => 2211000 }
city.each do |key, value|
puts “The city #{key} is #{value}”
end
The city name is Paris
# The city population is 2211000
What Regexp anchor would you use to specify that the pattern you look for is at the end of a string?
It’s \z, for instance:
/abc\z/ # any abc pattern found at the end of a string
What operator would you use to get the position of a Regexp pattern matched in a String?
It’s =~, for instance:
“hello” =~ /l{2}/ # => 2
“hello” =~ /m{2}/ # => nil
What method should you use when you want to get all sequences matching a Regexp pattern in a String?
You should use #scan which returns an Array of matching sequences, whereas =~ and #match will return info about the first match only.
Do you know how to use #gsub with a Regexp?
You can pass a Regexp as a first argument gsub(pattern, replacement), e.g.:
“Casanova”.gsub(/[aeiou]/, “i”)
# => “Cisinivi”
# replaces all vowels by the letter “i”
How do you parse a .json file in Ruby?
require “json”
filepath = “path/file.json”
serialized_file = File.read(filepath)
file_hash = JSON.parse(serialized_file)
How do you parse a .json file from an API?
First, you need open from OpenUri module and then you need JSON.parse from JSON module.
require “json”
require “open-uri” ###allows open url’s###
api_url = “https://v2.jokeapi.dev/joke/programming”
URI.open(api_url) do |stream|
quote = JSON.parse(stream.read)
puts quote[“setup”]
puts quote[“delivery”]
end
How do you store data in a .json file?
You need to use JSON.generate from the JSON module.
require “json”
beatles_hash = {
first_name: “John”,
last_name: “Lennon”,
instrument: “Guitar”
}
File.open(filepath, “w”) do |file|
file.write(JSON.generate(beatles_hash))
end
What Ruby type is stored in the row in this .csv file parsing?
CSV.foreach(filepath, { headers: true }) do |row|
puts row
end
A Ruby CSV::Row (similar to a Ruby hash).
row.class
=> CSV::Row
How can you open a web page in Ruby?
You need to use open from OpenUri module.
require “open-uri”
url = “https://www.lewagon.com”
html_content = URI.open(url).read
puts html_content
What Ruby type is stored in the row block parameter in this .csv file parsing?
CSV.foreach(filepath) do |row|
puts row
end
A Ruby Array.
row.class
#=> Array
How do you find the elements with a given selector from a scraped .html document?
You need to use Nokogiri::HTML::search from Nokogiri gem.
html_doc.search(“selector”).each do |element|
puts element.text
end
How do you store data in a .csv file?
You need to use CSV::open (http://ruby-doc.org/stdlib/libdoc/csv/rdoc/CSV.html).
require “csv”
filepath = “beatles.csv”
CSV.open(filepath, “wb”) do |csv|
csv «_space;[“First Name”, “Last Name”, “Instrument”]
csv «_space;[“John”, “Lennon”, “Guitar”]
csv «_space;[“Paul”, “McCartney”, “Bass Guitar”]
end
How do you store data in a .xml file?
You need to use Nokogiri::XML::Builder from Nokogiri gem
require “nokogiri”
filepath = “beatles.xml”
builder = Nokogiri::XML::Builder.new(encoding: “UTF-8”) do
beatles do
title “The Beatles”
beatle do
first_name “John”
last_name “Lennon”
instrument “Guitar”
end
beatle do
# […]
end
end
end
File.open(filepath, “w”) { |file| file.write(builder.to_xml) }
How do you parse a .csv file row by row?
ou need to use CSV::foreach
Consider beatles.csv:
“John”,”Lennon”,”Guitar”
“Paul”,”McCartney”,”Bass Guitar”
And the script:
require “csv”
filepath = “/my_folder/beatles.csv”
CSV.foreach(filepath) do |row|
puts “#{row[0]} #{row[1]} played #{row[2]}”
end
“John Lennon played Guitar”
# “Paul McCartney played Bass Guitar”
How do you parse a local .xml file (3 steps)?
require “nokogiri”
step 1: Open the .xml file
file = File.open(“beatles.xml”)
step 2: Convert the .xml file in a Nokogiri::XML document
document = Nokogiri::XML(file)
step 3: You can iterate through elements of the Nokogiri::XML document
document.root.xpath(“beatles”).each do |beatle|
first_name = beatle.xpath(“first_name”).text
last_name = beatle.xpath(“last_name”).text
instrument = beatle.xpath(“instrument”).text
puts “#{first_name} #{last_name} played #{instrument}”
end
How do you scrape every chocolate recipe name and URL from allrecipes recipe website?
require “open-uri”
require “nokogiri”
url = “https://www.allrecipes.com/search?q=chocolate”
html_file = URI.open(url).read
html_doc = Nokogiri::HTML.parse(html_file)
html_doc.search(“.mntl-card”).each do |element|
puts element.search(“.card__title-text”).text.strip
puts element.attribute(“href”).value.strip
end
What’s the class constructor method name in Ruby?
The constructor is the #new method called on a class (here Dog) to create an instance (here rex) of this class.
It creates the instance, calls the #initialize method on it and returns it.
class Dog
def initialize(name, breed)
@name = name
@breed = breed
end
end
rex = Dog.new(“Rex”, “German Sheperd”)
# => #<Dog:0x007f9423a86f10 @name=”Rex” @breed=”German Sheperd”>
You need to pass to #new as many arguments as the #initialize method requires
Consider the following Student class:
class Student
def initialize(first_name)
@first_name = first_name
@tired = false
end
def went_out_late_last_night
@tired = true
end
def fresh
!@tired
end
end
What’s missing in #went_out_late_last_night and #fresh instance methods to be compliant with Ruby conventions?
went_out_late_last_night changes the instance’s state, it should end with !
What does overriding of a superclass method mean?
You override a superclass method when you re-define or complete a superclass method in a subclass.
Do you know what a class method is and how to define one?
A class method is a method existing in the context of the class itself, not an instance (so they never have access to instance variables and methods). You must name it like self.my_method, and it can be called directly on the class like MyClass.my_method.
class Restaurant
def self.categories
[‘Fast Food’, ‘Italian’, ‘Japanese’, ‘Oriental’]
end
end
Restaurant.categories
# => [‘Fast Food’, ‘Italian’, ‘Japanese’, ‘Oriental’]
What does the super keyword do?
super calls the parent’s method which has the same name.
What’s the role of the Controller in a 1-model Task manager in Ruby?
The Controller’s role is to:
fetch data from the TaskRepository and send it to the View,
receive data from the View and send it to the TaskRepository.
The Controller is often compared to a conductor because of its role of pivot!
What should you require_relative in the Controller in a 1-model Task manager in Ruby?
You should require_relative the task model and the view, in order to instantiate a View.new in #initialize and a Task.new in the #create_task action.
In a Controller, the instance methods are referred to as …?
The Controller’s instance methods are referred to as actions, because they are the actions available to a user running the app (create a task, update a task, destroy a task…).
They usually match the user stories, in other words, the features of the app.
How to read a CSV file in Ruby?
Use the CSV.foreach method to read the CSV file. This method will yield each row of the CSV file as an array.
CSV.foreach(‘path/to/your/file.csv’) do |row|
# Each row is an array representing the columns of the CSV
puts row.inspect # Print the array representing the row
end
How to write in a CSV File?
CSV.open(‘file.csv’, ‘w’) do |csv|
# Code inside this block operates on the CSV file
end
What does serialization refer to in data storing?
The process of converting a dynamic object to binary data (or string) is called serialization.
Ruby objects vanish when the app closes. To be able to launch the app again with the data, we save all information about the actual state of objects in a database (or a text file).
Properties, relations, etc. are all converted to binary data (or string) to be persisted.
Why do we need IDs in our models?
We need them to translate relations between tables in a database.
In a table’s row, a reference to another table’s record is called a foreign key.
We don’t need them in the objects world, as we can store objects in instance variables, but we have no choice but to use id’s to track references between records from different tables in a database!
In a 2-model (Patient, Room) app, how would you model the following relationship in your CSV files:
A room has several patients,
A patient stays in a room?
Both CSV files have an id column to store a unique identifier by record.
The patients.csv file has a room_id column to store the id of the patient’s room he stays in, also called a foreign key.
In a parent-children relationship (a room has many patients), it’s always the children who carry the relationship.
In a 2-model (Patient, Room) app, how would you model the following relationship in your models:
A room has several patients,
A patient stays in a room?
- A Room has a @patients instance variable storing the instances of Patient it hosts;
- A Patient has a @room instance variable storing the instance of Room he’s in.
You usually expose those instance variable to reading with attr_readers, to be able to call .patients on a Room instance and .room on a Patient instance.
Always use objects when you’re on the “Ruby side” of your program (vs the “CSV side”)!
In a 2-model (Patient, Room) app, how would you model the following relationship in your CSV files:
A room has several patients,
A patient stays in a room?
Both CSV files have an id column to store a unique identifier by record.
The patients.csv file has a room_id column to store the id of the patient’s room he stays in, also called a foreign key.
In a parent-children relationship (a room has many patients), it’s always the children who carry the relationship.
How do you Create (CRUD) in SQL?
Using the INSERT INTO keyword:
INSERT INTO doctors (name, age, specialty)
VALUES (‘Dr House’, 42, ‘Diagnostic Medicine’);
We don’t insert the id, because the database manages it automatically for us (autoincrement).
Given a 3-table (doctors, patients, appointments) schema, write a single SQL query that will return all of these criteria for each consultation:
consultation’s date,
the patient’s first name and last name,
the doctor’s first name and last name?
SELECT a.starts_at, p.first_name, p.last_name, d.first_name, d.last_name
FROM appointments a
JOIN patients p ON a.patient_id = p.id
JOIN doctors d ON a.doctor_id = d.id;
What is the SQL keyword to specify a filtering condition clause in a query?
WHERE:
SELECT * FROM doctors WHERE specialty = “Cardiac surgery”;
What is the SQL keyword to join two tables in a query?
JOIN … ON …:
SELECT * FROM first_table
JOIN second_table ON second_table.id = first_table.second_table_id;
How do you Update (CRUD) in SQL?
Using the UPDATE keyword:
UPDATE doctors SET age = 40, name = ‘John Smith’ WHERE id = 3;
How do you Delete (CRUD) in SQL?
Using the DELETE keyword:
DELETE FROM doctors WHERE id = 32;
Warning, if you omit the WHERE statement, you will delete every record in your table!
How do you retrieve all instances of a given Active Record model in Ruby?
By calling .all on your model!
doctors = Doctor.all
# => returns a collection (~ array) of all Doctor instances.
ActiveRecord Basics:
How do you run pending migrations?
rake db:migrate
From what Active Record class should your models inherit?
They should inherit from ActiveRecord::Base
class Doctor < ActiveRecord::Base
end
No attr_accessor or #initialize needed, Active Record takes care of everything ;)
What is the SQL query generated by Doctor.all?
SELECT * FROM doctors;
Note that every Active Record query generates an SQL query that you can read in your application logs in your terminal!
From what class should your migrations inherit?
They should inherit from ActiveRecord::Migration
class CreateDoctors < ActiveRecord::Migration[7.0]
[…]
end
How do you retrieve the number of instances of a given Active Record model?
By calling .count on your model!
Doctor.count
# => returns the number of Doctor instances (Integer).
Complete the following migration to create a doctors table with a name and a specialty
class CreateDoctors < ActiveRecord::Migration[7.0]
def change
# TODO
end
end
def change
create_table :doctors do |t|
t.string :name
t.string :specialty
t.timestamps # adds 2 columns, created_at
and updated_at
end
How do you retrieve a specific record of a given Active Record model?
By calling .find(id) on your model!
first_doctor = Doctor.find(1)
# => returns the instance of Doctor with the id 1
If you don’t know the id of the record you want to retrieve, you can also call .find_by(attribute: value):
house = Doctor.find_by(name: “Greg House”)
# => returns the first instance of Doctor with the name “Greg House”
ActiveRecord Basics
Complete the following migration to add an age column to the doctors table.
class AddAgeToDoctors < ActiveRecord::Migration[7.0]
def change
# TODO
end
end
def change
add_column :doctors, :age, :integer
end
ActiveRecord Basics:
How do you retrieve all doctors of a given specialty?
surgeons = Doctor.where(specialty: “Surgeon”)
# => returns a collection (~ array) of all surgeons.
You can also pass a string as an argument to the .where class method:
young_doctors = Doctor.where(“age < 35”)
# => returns a collection (~ array) of all doctors under 35 years old.
surgeons = Doctor.where(“specialty LIKE %surgery%”)
# => returns a collection (~ array) of all doctors with ‘surgery’ in their specialty.
And last:
dentists_and_surgeons = Doctor.where(specialty: [“Dentist”, “Surgeon”])
ActiveRecord Basics
Consider the following model:
class Doctor < ActiveRecord::Base
end
Assuming you already created a DB with a doctors table, how would you add a new doctor in your DB?
By instantiating a Doctor and calling #save on it:
dr_house = Doctor.new(name: “Greg House”)
dr_house.save
# => INSERT INTO doctors (name) VALUES (‘Greg House’);
Or with the create class method directly:
dr_house = Doctor.create(name: “Greg House”)
# => INSERT INTO doctors (name) VALUES (‘Greg House’);