Ruby Le Wagon Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

Commenting in Ruby?

A

#

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Two Types of Numeric Numbers in Ruby?

A

Integer for whole numbers

Float for decimal numbers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to determine the type of data in Ruby?

A

.class

name = “Dimitri”
puts name.class # => will return String

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Checking for odd or even in Ruby?

A

10.even? # => will return true
22.odd? # => will return false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Changing an object in a string in Ruby?

A

.to_s

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to get an integer from a float in Ruby?

A

.round

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Upper Case, capitalizing, reversing in Ruby?

A

.upcase, .capitalize, .reverse

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to sort arrays in Ruby?

A

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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Converting Strings to Numbers in Ruby?

A

to_i –> string to interger
to_f –> string to float

e.g.
“5”.to_i —> 5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Shorthand in Ruby for converting a method into a block

A

&:

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Converting Numbers to String in Ruby?

A

With the ‘to_s’ method.

e.g.:
number = 42
string_number = number.to_s
puts string_number # Output: “42”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How to get the highest and/or lowest numbers of an array in Ruby?

A

.min
.max

.minmax –> array of the highest and lowest number

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How does the fetch method work?

A

.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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Bash command for the filepath of the current directory?

A

pwd (print working directory)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Bash command that lists files and directories in current directory?

A

ls

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Bash command that navigates from one folder to another?

A

cd path/to/go

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Bash command that creates a new directory?

A

mkdir folder_name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Bash command that creates a new file?

A

touch file_name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Bash command that moves the file into the directory?

A

mv file_name path/to/directory?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Bash command that removes a file?

A

rm path/to/file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Bash command that display the content of a file?

A

cat file_name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

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?

A

.scan(>pattern<)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How to delimit a regular expression pattern in Ruby?

A

With two forward dashes:

/…/

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What are character classes in Ruby?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

How can you concatenate the items of an array in Ruby?

A

.join(“…”)

… = the characters between the items

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What are the exclusive and inclusiv operators in Ruby?

A

… is exclusiv (0…3&raquo_space; 0, 1, 2)

.. is inclusive (0..3)» 0, 1, 2, 3)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

How to split a String sentence into an Array of words in Ruby?

A

“string”.split(“ “)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Do you know a shortcut to define an array of strings in Ruby?

A

There are three ways you can define an array of strings without typing quotes

%w[Huey Dewey Louie] #=> [“Huey”, “Dewey”, “Louie”]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is the main difference between single quotes ‘ and double quotes “ in Ruby?

A

You can only interpolate between double quotes:

“two: #{1 + 1}”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

How can you get the position (index) of an item in an array in Ruby?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Do you know the best way to iterate through the items of an array in Ruby?

A

[1, 2, 3].each do |num|
puts num
end

[1, 2, 3].each { |num| puts num }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

How can you delete an item from an array in Ruby?

A

.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”]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What is the opposite of while in Ruby?

A

until:

until condition
# loops while condition is falsy
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

How can you test if an item is included in an array in Ruby?

A

.include?

beatles = [“John”, “Ringo”, “Paul”, “George”]
beatles.include?(“John”) #=> true
beatles.include?(“Boris”) #=> false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Is there a way to have the index and the element when you iterate through an Array in Ruby?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Which iterator should you call on an Array to get another Array where all the elements were subject to the same treatment in Ruby?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

How can you group Array items by pair or more in Ruby?

A

.each_slice(no. of items).to_a

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

How do you remove items matching a condition from an Array in Ruby?

A

.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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

How would you sort an Array with a given sorting criteria in Ruby?

A

.sort_by

[“apple”, “pear”, “fig”].sort_by { |word| word.length }
#=> [“fig”, “pear”, “apple”]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

How would you find the first element of an Array that satisfies a given condition in Ruby?

A

.find

musicians = [“Jimmy Page”, “Robert Plant”, “John Paul Jones”, “John Bonham”]

musicians.find { |musician| musician.split(“ “).first == “John” }
# => “John Paul Jones”

41
Q

How do you count the number of Array elements matching a condition in Ruby?

A

.count

musicians = [“Jimmy Page”, “Robert Plant”, “John Paul Jones”, “John Bonham”]

musicians.count { |musician| musician.include? “J” }

=> 3

42
Q

How can you tell if a key is present in a Hash?

A

hash.key? :key

boris = {
first_name: “Boris”,
github_nickname: “Papillard”
}

boris.key? :first_name
# => true

boris.key? :email
# => false

43
Q

What method should you use on a Hash if you just need to iterate over its keys?

A

.each_key

boris.each_key do |key|
puts “Boris has a #{key}”
end

44
Q

How can you get all the values of a Hash in an array?

A

.values

boris = {
first_name: “Boris”,
github_nickname: “Papillard”
}

boris.values
# => [“Boris”, “Papillard”]

45
Q

When should you use a Symbol to store text, and when should you use a String?

A

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.

46
Q

What iterator should you use on a Hash if you just need to operate on its values?

A

.each_value

boris.each_value do |value|
puts “#{value} is an attribute of boris”
end

47
Q

How can you retrieve all the keys of a Hash into an array?

A

.keys

boris = {
first_name: “Boris”,
github_nickname: “Papillard”
}

boris.keys
# => [:first_name, :github_nickname]

48
Q

How can you tell if a value is present in a Hash?

A

.value?

boris = {
first_name: “Boris”,
github_nickname: “Papillard”
}

boris.value?(“Boris”)
# => true

49
Q

What is a Symbol?

A

A Symbol is a built-in Ruby object used to represent text.
It is characterized by its : prefix, e.g. :city

50
Q

How can you iterate through a Hash?

A

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

51
Q

What Regexp anchor would you use to specify that the pattern you look for is at the end of a string?

A

It’s \z, for instance:

/abc\z/ # any abc pattern found at the end of a string

52
Q

What operator would you use to get the position of a Regexp pattern matched in a String?

A

It’s =~, for instance:

“hello” =~ /l{2}/ # => 2
“hello” =~ /m{2}/ # => nil

53
Q

What method should you use when you want to get all sequences matching a Regexp pattern in a String?

A

You should use #scan which returns an Array of matching sequences, whereas =~ and #match will return info about the first match only.

54
Q

Do you know how to use #gsub with a Regexp?

A

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”

55
Q

How do you parse a .json file in Ruby?

A

require “json”

filepath = “path/file.json”

serialized_file = File.read(filepath)

file_hash = JSON.parse(serialized_file)

56
Q

How do you parse a .json file from an API?

A

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

57
Q

How do you store data in a .json file?

A

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

58
Q

What Ruby type is stored in the row in this .csv file parsing?

CSV.foreach(filepath, { headers: true }) do |row|
puts row
end

A

A Ruby CSV::Row (similar to a Ruby hash).

row.class

=> CSV::Row

59
Q

How can you open a web page in Ruby?

A

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

60
Q

What Ruby type is stored in the row block parameter in this .csv file parsing?

CSV.foreach(filepath) do |row|
puts row
end

A

A Ruby Array.

row.class
#=> Array

61
Q

How do you find the elements with a given selector from a scraped .html document?

A

You need to use Nokogiri::HTML::search from Nokogiri gem.

html_doc.search(“selector”).each do |element|
puts element.text
end

62
Q

How do you store data in a .csv file?

A

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 &laquo_space;[“First Name”, “Last Name”, “Instrument”]
csv &laquo_space;[“John”, “Lennon”, “Guitar”]
csv &laquo_space;[“Paul”, “McCartney”, “Bass Guitar”]
end

63
Q

How do you store data in a .xml file?

A

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) }

64
Q

How do you parse a .csv file row by row?

A

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”

65
Q

How do you parse a local .xml file (3 steps)?

A

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

66
Q

How do you scrape every chocolate recipe name and URL from allrecipes recipe website?

A

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

67
Q

What’s the class constructor method name in Ruby?

A

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

68
Q

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?

A

went_out_late_last_night changes the instance’s state, it should end with !

69
Q

What does overriding of a superclass method mean?

A

You override a superclass method when you re-define or complete a superclass method in a subclass.

70
Q

Do you know what a class method is and how to define one?

A

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’]

71
Q

What does the super keyword do?

A

super calls the parent’s method which has the same name.

72
Q

What’s the role of the Controller in a 1-model Task manager in Ruby?

A

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!

73
Q

What should you require_relative in the Controller in a 1-model Task manager in Ruby?

A

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.

74
Q

In a Controller, the instance methods are referred to as …?

A

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.

75
Q

How to read a CSV file in Ruby?

A

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

76
Q

How to write in a CSV File?

A

CSV.open(‘file.csv’, ‘w’) do |csv|
# Code inside this block operates on the CSV file
end

77
Q

What does serialization refer to in data storing?

A

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.

78
Q

Why do we need IDs in our models?

A

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!

79
Q

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?

A

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.

80
Q

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
  • 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”)!

81
Q

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?

A

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.

82
Q

How do you Create (CRUD) in SQL?

A

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).

83
Q

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?

A

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;

84
Q

What is the SQL keyword to specify a filtering condition clause in a query?

A

WHERE:

SELECT * FROM doctors WHERE specialty = “Cardiac surgery”;

85
Q

What is the SQL keyword to join two tables in a query?

A

JOIN … ON …:

SELECT * FROM first_table
JOIN second_table ON second_table.id = first_table.second_table_id;

86
Q

How do you Update (CRUD) in SQL?

A

Using the UPDATE keyword:

UPDATE doctors SET age = 40, name = ‘John Smith’ WHERE id = 3;

87
Q

How do you Delete (CRUD) in SQL?

A

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!

88
Q

How do you retrieve all instances of a given Active Record model in Ruby?

A

By calling .all on your model!

doctors = Doctor.all
# => returns a collection (~ array) of all Doctor instances.

89
Q

ActiveRecord Basics:
How do you run pending migrations?

A

rake db:migrate

90
Q

From what Active Record class should your models inherit?

A

They should inherit from ActiveRecord::Base

class Doctor < ActiveRecord::Base
end
No attr_accessor or #initialize needed, Active Record takes care of everything ;)

91
Q

What is the SQL query generated by Doctor.all?

A

SELECT * FROM doctors;
Note that every Active Record query generates an SQL query that you can read in your application logs in your terminal!

92
Q

From what class should your migrations inherit?

A

They should inherit from ActiveRecord::Migration

class CreateDoctors < ActiveRecord::Migration[7.0]
[…]
end

93
Q

How do you retrieve the number of instances of a given Active Record model?

A

By calling .count on your model!

Doctor.count
# => returns the number of Doctor instances (Integer).

94
Q

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

A

def change
create_table :doctors do |t|
t.string :name
t.string :specialty
t.timestamps # adds 2 columns, created_at and updated_at
end

95
Q

How do you retrieve a specific record of a given Active Record model?

A

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”

96
Q

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

A

def change
add_column :doctors, :age, :integer
end

97
Q

ActiveRecord Basics:
How do you retrieve all doctors of a given specialty?

A

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”])

98
Q

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?

A

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’);