Anki cards for Ruby
Flashcards for Ruby. Created with Obsidian Anki Sync notation.
[TOC]
default value if variable is nil
::
# number MUST be nil!
# Doesn't work if it's an undefined var.
var = number || 5
default value if argument is not passed
::
def method(parameter = "default value")
# ...
end
declare a Class method to be called from the Class name
::
use self.method_name
:
class Hello
def self.world
"Hello World!"
end
end
autocreate getters/setters
::
use attr_accessor
:
class Person
attr_accessor :first_name, :last_name
end
what does String.count
do?
::
counts how many "char-set" there are in the string
>> 'meleu'.count('e')
=> 2
>> 'meleu'.count('el')
=> 3
how Array.map
works?::
returns a new array with the results of running a block once for every element in the array (enumeration)
# raise all numbers to square
>> [1, 2, 3].map { |num| num ** 2 }
=> [1, 4, 9]
get an array with no repeated items
::
# use .uniq method
>> [1, 2, 3, 4, 5, 2, 2, 4, 5].uniq
=> [1, 2, 3, 4, 5]
String.scan
vs. String.split
?
::
.scan
searches for the items, and accepts regex.split
searches for the separators, no regex
>> "item1--item2--itemN".split("--")
=> ["item1", "item2", "itemN"]
>> "item1--item2--itemN".split("-")
=> ["item1", "", "item2", "", "itemN"]
>> "item1--item2-:itemN".scan(/item./)
=> ["item1", "item2", "itemN"]
from char to ASCII value
::
'a'.ord # ordinal
# => 97
from ASCII value to char
::
97.chr
# => "a"
subtract arrays
::
[1, 2, 3] - [1, 3]
# => [2]
create an Array
from a Range
::
# n00b way
alphabet = ('a'..'z').to_a
# ninja way
alphabet = [*'a'..'z']
capture an Exception
::
begin
# ... code that can raise an exception...
rescue ExceptionName => e
# ... code to run when getting an exception
end
How do you clean an Array
from items matching a condition?
::
Using #reject
iterator (think of a negation of #select
)
a = [1, 2, 3, 4]
# reject the even numbers:
a.reject { |n| n.even? }
# => [1, 3]
How would you sort an Array
with a given sorting criteria?
::
Defining the criteria in a block to #sort_by
strings_array.sort_by do |word|
word.length
end
Generic syntax of a migration to add a column to a given table?
::
class AddColumnToTable < ActiveRecord--Migration[7.0]
def change
add_column :table, :column, :type
# table names are always plural!
end
end
What are the 4 most common ActiveRecord validation types?
::
presence
uniqueness
length { min or max }
format { with: /regex/ }
ActiveRecord: migration to rename a column?
::
rename_column :table, :old_column_name, :new_column_name
ActiveRecord: 1:n relation between doctors
and interns
written in the interns
migration
::
class CreateInterns < ActiveRecord--Migration[7.0]
def change
create_table :interns do |t|
t.references :doctor, foreign_key: true
# ...
end
end
end
ActiveRecord: migration to add an intern_id
foreign key in patients
table
::
class AddInternReferenceToPatients < ActiveRecord--Migration[7.0]
def change
add_reference :patients, :intern, foreign_key: true
end
end
ActiveRecord: migration to remove column from table
::
class RemoveColumnFromTable < ActiveRecord--Migration[7.0]
def change
remove_column :table, :column, :type
end
end
When a restaurant is destroyed, all of its reviews must be destroyed as well
::
class Restaurant < ApplicationRecord
has_many :reviews, dependent: :destroy
end
Strong Params for a Task
::
def task_params
params
.require(:task)
.permit(:title, :details, :completed)
end
Run a method before a collection of controller's action
::
# example for set_task
before_action :set_task, only: %i[show edit update destroy]
Simple Form installation
::
# Gemfile
# ...
gem 'simple_form'
bundle install
rails generate simple_form:install --bootstrap
Simple Form for a Task
::
simple_form_for @task do |f|
f.input :title
f.input :details
f.submit
end
5 steps of Rails assets pipeline
::
- precompile
- concatenate
- minify
- fingerprinting (for caching)
- compacting (gzip)
Routes for restaurants and reviews
::
resources :restaurants do
resources :reviews, only: %i[new create]
end
resources :reviews, only: :destroy
View: delete button with a confirmation
::
button_to(
"Delete",
@post,
method: :delete,
data: {
turbo_confirm: 'Sure?'
}
)