Ruby basics + advanced Flashcards
What is ruby?
It is a programming language
What does RVM stand for?
Ruby version manager
What does RVM let you do?
It lets you switch between different versions of ruby.
What are variables?
They are the building blocks of a program and they let you store information.
How much information can a variable store?
Variables can store a lot of data, full algoritms, blocks and lambdas
How do you set a variable in ruby?
you give it a name and set it equal to the information
ex variable_1 = ‘A string’
How can you print out objects to the terminal?
- puts
- p
What is puts?
puts will return nil and print out the object in a new line. Puts also iterates over the values.
What is p?
p will return the value and print out the object
How do you get user input form the terminal?
you use the gets method
What is chomp?
chomp deletes the extra character that your gets method adds to the input.
What kinds of variables are there?
- Local variables
- Global variables
- Instance variables
- Constants
- Class variables
What is a local variable?
A local variable is a variable that limits itself to a local scope of where it is declared.
It is only available to that specific method or package
What is a global variable?
A global variable written with a $ before the variable name is available all over the application. And it’s a terrible idea. because the last time you set the variable will declare it.
What is a instance variable?
An instance variable is written with a @ sign before the variable name.
The instance variable is available for that instance in other places.
What is a constant?
A constant is a variable is written with CAPITAL letters and is a variable that is not supposed to be changed.
What is a class variable?
A class variable is written with @@ is a variable that is available to that instance of the class.
What is a string?
A string is a object where you store a collection of characters. These must be contained in single or double quotes
What is string interpolation?
String interpolation is a method where you can display dynamic values inside a string. Everything between a #{ } will be embedded ruby. You must use double quotes on the string when working with string interpolation.
What is string manipulation?
String manipulation is when you use methods to change the strings.
what is a bang? ( ! )
When you see the ! in the end of a method it means that it is changing the original version of the variable .
What is string substitution?
String substitution is a method in ruby. You use .gsub!( ‘original’ , ‘the change’)
What is the strip method?
it removes the extra spaces in a string in the beginning and in the end of a string
What is the split method?
The split method converts each word in a string to an array.
What is the order of execution in ruby?
Please Excuse My Dear Aunt Sally =
Paranthesis, Exponents, Multiplication, Division, Addition, Subtraction
What is the difference between integers and floats?
A float has decimals and integer doesn’t.
make sure to use decimal to get the proper output.
What is the difference between floats and decimals?
Floats do not have many decimal points, but decimals can have a lot of numbers to be accurate.
How do you declare a method?
def snake_case
some logic
end
How do you call/run a method?
you just type the method name
What is the difference between puts and return
puts is used for debugging purposes and does not store a value.
return prints and stores the value and is used in production applications.
What is the difference between a class method and a instance method?
You can call the class method directly on the class But you need to create an instance to be able to call an instance method.
ex
SomeClass.some_class_method
ex
variable = Invoice.new
variable.some_instance_method
How do you write a class method?
you add self before the method name in a class method.
def self.method_name
something
end
How do you call a class with a class method
SomeClass.some_class_method
What are Procs?
Procs are blocks of code (methods) that can be stored inside variables.
How do you write a Proc?
ex
variable = Proc.new { |argument1, argument2 | some code }
or ex variable = Proc.new do | argument1, argument 2 | some code end
How do you call a Proc?
proc_variable[ argument1, argument2]
or
proc_variable.call(argument1, argument2)
How do write a lambda?
variable = lambda { |argument1, argument2 | some code }
or
variable = -> (argument1, argument2) { |argument1, argument2 | some code }
How do you call a lambda?
lambda_variable[ argument1, argument2]
or
lambda_variable.call(argument1, argument2)
What is the difference between a Proc and Lambda?
1 lambdas count the number of arguments given (you must give right number of arguments).
2 Procs do not count the arguments (Procs ignore excess arguments).
3 Procs and lambdas have return differences. Procs do not return everything but lambdas do
What are method arguments?
The method arguments are the raw material provided by the user.
What are named arguments?
It is when you need to name your arguments when calling them, good for readability, to avoid confusion and you can give arguments in random order.
ex def write_name(first_name: , last_name: ) puts first_name puts last_name end
write_name(first_name: “Faraz”, last_name: “Naeem”)
What are default arguments?
Default arguments are arguments that are already written in the method, so that you only need to write out the argument when you want to overwrite the argument in the method.
What is a splat argument?
A Splat argument allows you to pass in multiple arguments into a method but it treats the arguments like an array.
ex
def method(*players)
some_code
end
method(argument1, argument2, argument3, argument4 …)
What is a keyword based splat argument?
a keyword based splat argument allows you to pass in an hash, then the
def method(**players)
some_code
end
method(some_hash)
What are optional arguments?
Optional arguments allows you to use arguments that you specifically want, and it will ignore other.
ex
def method_name(options ={})
puts [:some_key]
end
method_name(some_key: “hej”, another_key: “då”)
=> hej
What is a while loop?
It is a bit of code that will run as long as the conditions are true, it is very important to increment the value otherwise the loop will run forever.
while i < 10
puts “hey”
i += 1
end
What is the each loop?
the each loop is an iterator.
ex
variable.each do |value|
some_code for value
end
ex
variable.each { |value| some code for value}
What is the for loop?
the for loop executes code once for each element in expression.
ex
for i in 0..4
puts i
end
ex
for variable [, variable …] in expression [do]
code
end
What is an nested iterator?
It is when you are iterating on a collection inside another collection. (two hashes inside one hash)
ex
hash.each do | main_hash_value, sub_hash | puts main_hash_value sub_hash.each do |key, value| some code end end
What is the select method?
The select method selects a value from a collection and runs your code.
ex
(1..10).to_a.select do |value|
value.even?
end
ex
(1..10).to_a.select { |value| value.even? }
ex
(1..10).to_a.select(&:even?)
What is the map method?
The map method takes an enumerable object and a block and runs the block for each object.
ex
array.map { |value| value.some_method }
ex
array.map(&:some_method)
What is the inject method?
The inject method is used to combine number (addition subtraction, multiplication and so on)
ex array.inject(&:+) ex array.inject(&:-) ex array.inject(&:*)
How do you create an array?
ex
x = [1, 2, 34 ]
ex
y = Array.new
y[0] = 543
How do you remove items from an array?
you can use the delete method
ex (by the values)
array.delete(values)
ex (by index)
array.delete_at(index)
ex ( by if)
array.delete_if { |value| some_code }
What is the join method?
The join method is used to join the different values in an array
ex
array = [1, 2, 3]
array.join(‘+’)
=> “1+2+3”
What is the push method?
The push method is when you add an element to an array at the end of the array
ex
array = [1, 2, 3]
array.push(4)
=> [1, 2, 3, 4]
What is the pop method?
The pop method is used to delete the last element in an array.
ex
array = [1, 2, 3, 4]
array.pop
=> [1, 2, 3]
How do you add an element to an array=
You add them
by push or by index
ex
array[index] = value
What is a hash?
A hash is an key value collection (also called dictionary)
How do create an hash?
ex (modern syntax)
hash = {first: 1, second: 2}
ex (old syntax)
hash = {“first” => 1, “second” => 2}
ex (old, but with symbol)
hash = {:first => 1, :second => 2}
How do you return a value from an hash based on a key?
hash[:key]
How do you delete an element from an hash?
with the delete method
ex
hash.delete(:key)
How do you iterate over just the keys in a hash?
You use the each_key method
ex
hash.each_key do |key|
some_code
end
How do you iterate over just the values in a hash?
You use the each_value method
ex
hash.each_value do |value|
some_code
end
How do you add to a hash?
hash[:key] = value
How do you reverse the keys and the values in a hash?
you use the invert method
ex
hash = {:first => 1, :second => 2}
hash.invert
=> {1 => :first, 2 => :second}
How do you merge two hashes?
with the merge method
ex
hash.merge(another_hash)
How do you convert a hash to an array
hash.to_a
How do write an if statement?
ex if condition some_code elsif condition some_code else some_code end
ex (simple)
some_code if conditional
What is an unless statement?
An unless statement runs code unless some condition becomes true
ex
unless conditional
some_code
end
ex
some_code unless conditional
How do you chain multiple conditionals together(compund conditional)?
With the && or || methods
ex (and symbol both must be true)
if conditional && conditional
some_code
end
ex (or symbol one must be true)
if conditional || conditional
some_code
end
How do you set up a class in ruby?
ex class ClassName
end
everything within the class will belong to the class
What is an initializer method?
It is a method that will run some code every time you create a new instance of the class. The initialize method will need some arguments that you need to pass in when you are creating a new instance of the class.
ex
def initialize(argument1, argument2)
some_code
end
Why is inheritance important?
In order not to repeat code it is easier to give inheritance to other classes. than rewrite the code for every class.
You have a parent class and the other classes (children) inherit from it.
How many responsibilities should a class have?
only one
What is a public method?
It means that the method is visible to others.
What is private method?
It means that only that specific class has access to that specific methods.
A secret method should only be called from within the class.
What is polymorphism?
It is when you override a method from a parent class with a method from a child class. You use polymorphism to give custom behaviour.
What is the super keyword?
It is when you want the same method both in the parent and child class to be called, instead of the child class method overriding the parent class method (polymorphism)
You write the super keyword in the child class whitin the method when you want it to be called.
How do you create a file?
ex
File.open(“file-path”, ‘options’) { |x| x.write(“something to write”)}
ex (alternate way)
variable = File.new(“file-path”, ‘options’)
variable.puts(“Some content”)
variable.close
options : r - reading a - appending to a file w - just writing w+ reading and writing a+ open a file for reading and appending r+ - opening a file for updating both reading and writing
How do you read from a file?
ex
variable = File.read(“file path”)
you can now treat the content of the file as you want.
How do you delete a file?
ex
File.delete(“file path”)
How do you update a file in ruby?
ex ( will add stuff to the file)
File.open(“file path” “a”) {|f| some_code}
What is the basic syntax for error handling in ruby?
not using Rspec
ex begin some code rescue some code end
How should you write errors in ruby? (not using Rspec)
ex begin some code rescue StandarError => variable puts "error message #{variable}" end
What is a regular expression?
A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings using a specialized syntax held in a pattern.
what is the basic syntax for regular expressions?
=~ /matcher/
What is grep?
Grep is a method that is used to search through collections and objects.
ex
array.grep(search_object)
What are ruby gems?
Ruby gems are basically ruby code packaged.
What is metaprogramming in ruby?
It is the process of writing code that writes itself during runtime.
What is the w%( ) method?
it allows you to create an array from a string without adding commas and such.
What is the freeze method?
The freeze method makes an object unable to change.
How do you interact with an API with ruby?
You need a gem (httparty) to interact and you also need a class with methods.
What is a URI?
Uniform Resource Identifiers is a string of characters used to identify a resource.
The most common form of URI is the Uniform Resource Locator (URL),
Do you need to use a web framework like Rails or Sinatra to work with APIs?
No
What is a popular gem for working with APIs?
httparty
What type of data is typically sent back as an API response?
JSON
What is the sort method?
The sort method allows you to sort the elements inside an array.
What is the super keyword?
super calls the method of the parent class, if it exists. it passes all the arguments to the parent class method as well.
What are modules?
Modules are a way of grouping together methods, classes, and constants.
Modules give you two major benefits.
- Modules provide a namespace and prevent name clashes.
- Modules implement the mixin facility.
What is a mixin
Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the class that uses it.
A mixin can basically be thought of as a set of code
that can be added to one or more classes to
add additional capabilities without using inheritance.
What is the & prefix?
the & prefix allows us to pass in a code block as a parameter like { print ‘Ho!’ }
What is Ruby?
Ruby is a high-level programming language
- Ruby is Interpreted (no need for a compiler)
- Object-oriented (allows users to manipulate data structures)
- Easy to use
What kind of data types are there in Ruby?
Integer = Number Numeric = class of number like float, fixnum Float = decimal number NilClass = The class of the singleton object nil. Hash = A Hash is a dictionary-like collection of unique keys and their values. Symbol = Symbol objects represent names and some strings inside the Ruby interpreter. Array = A list of objects Range = A Range represents an interval—a set of values with a beginning and an end.
What is a variable?
One of the most basic concepts in computer programming is the variable. You can think of a variable as a word or name that grasps a single value.
my_num = 25
What arithmetic operator are there in ruby?
addition +
subtraction -
multiplication *
division /
modulo %
exponentiation **
What is the difference between puts and print?
print just prints whatever you give it to the screen
puts (“put string”) prints out what you give it with an empty line
So the difference is that puts has one more line
added.
What is a method in ruby?
They are built in abilities that objects have.
For example methods can show you the length of a string or reverse the string.
What is an interpreter?
An interpreter is a program that takes your code and runs it, it shows the result in your console
How do you use a method?
Methods are used with a .
my_string = ‘i love pizza’ –> my_string.length –> 12
How do write a comment in ruby?
you use #
Everything behind the (on the same line) # will be commented out
How do you do a multiline comment in Ruby?
You use =begin and =end
Everything in between will be commented out, you can use this to explain complicated concepts.
What is a naming convention?
A naming convention is how the community writes code, local variables should be written in lowercase letters and words.
How do you declare or set a variable?
You use the =
my_number = 12
How can you call multiple methods on a variable?
by chaining
name.method1.method2.method3
What is chaining?
Chaining is that you call multiple methods on a variable
What is control flow?
Control flow is that we can select different outcomes depending on the environment and the input.
What is an if statement?
Ruby takes an if statement and decides if its true and runs code accordingly.
What is an else statement?
The else statement is the continuation of the if statement. This code runs after the if statement is false.
What is an elsif statement?
An elsif statement gives the if else statement more options.
What is an unless statement?
An if statement checks if something is true, An unless statement checks if something is false and runs code accordingly.
What is a comparator?
A comparator checks if two values are equal or not
we use == to check if they are equal and != if we want to check if two values are not equal.
What are the comparator for less or equal than?
less than <
less than or equal to <=
greater than >
Greater than or equal to >=
What are boolean operators?
Boolean operators are either true or false
- && (and)
- | | (or)
- ! (not)
What is an and operator?
- && (and), The expression is true if both statements before and after && are true
true && true => true
true && false => false
false && true => false
false && false => false
What is an Or-operator?
- | | (or) is an operator when at least one of the expressions are true
true || true # => true
true || false # => true
false || true # => true
false || false # => false
What is an Not-operator?
A not operator (!) makes any statement after the expression false
!true= false
What is gets.chomp?
Gets chomp is for getting user input from the terminal
What is the .downcase method?
the .downcase method takes the user input and converts it do lower case letters.
What is the .include? method
The include? method checks if the user input contains what we want
What is the .gsub! method?
The .gsub method stands for global substitution and changes all the chosen inputs.
string_to_change.gsub!(/s/, “th”)
What is string interpolation ?
String interpolation adds a value to a string.
print “Adios, #{my_string}!”
What is a While loop?
The while loop runs code as long as the conditions are true.
counter = 1 while counter < 11 puts counter counter = counter + 1 end
What is an infinite loop?
An infinite loop is a loop that runs forever.
They need to be avoided at all cost.
What is an untill loop?
An until loop runs as long as the conditions are not met.
i = 0 until i == 6 i = i + 1 end puts i
What is an assignment operator?
An assignment operator is used to update a variable.
+=, -=, *=, and /=.
What is an for loop?
The for loop runs a code between a range.
for current_iteration_number in 1..100 do
puts “Hello world, this is number #{current_iteration_number}”
end
What is an inclusive range?
An inclusive range is a range that includes the last number in the range
1..3 (two dots)
for num in 1..20 (don’t forget the in)
puts num
end
What is an exclusive range?
An exclusive range is a range where the last number is not included in the range.
1..3 (three dots)
for num in 1…20 (don’t forget the in)
puts num
end
What is an iterator?
An iterator is just a Ruby method that repeatedly invokes a block of code.
What is the next keyword?
The next keyword is used to skip a step.
What is an array?
An array is a variable with multiple items in it
my_array = [1, 2, 3, 4]
An array is also indexed starting from 0.
How do you get user input?
gets.chomp
What is The .each Iterator ?
.each method, which can apply an expression to each element of an object, one at a time.
object.each do | item | # Do something end
What is the .times Iterator?
The .times method is like a super compact for loop: it can perform a task on each item in an object a specified number of times
10.times { print “Chunky bacon!” }
What is the .split Method?
it takes in a string and returns an array. If we pass it a bit of text in parentheses, .split will divide the string wherever it sees that bit of text, called a delimiter. For example,
text.split(“,”)
What is an array index?
Each element in the array has what’s called an index. The first element is at index 0, the next is at index 1, the following is at index 2, and so on.
How do you access an object in an array with the index?
With brackets
array = [5, 7, 9, 2, 0]
array[2]
# returns “9”, since “9”
# is at index 2
What are multidimensional arrays?
It’s an array of arrays
What are hashes?
A hash is a collection of key-value pairs
How do you create a hash?
You use the Hash.new method.
by setting a variable to Hash.new
my_hash = Hash.new
How do you add objects to a hash?
We add object to hash with bracket notation:
pets = Hash.new pets["Stevie"] = "cat"
How do you accesses objects in a hash?
We accesses it by using the same method like an array:
puts pets[“Stevie”]
pets = { "Stevie" => "cat", "Bowser" => "hamster", "Kevin Sorbo" => "fish" }
puts pets[“Stevie”]
What do we call it when we loop over a hash or an array?
We call it that we iterate over the hash or array.
How do we iterate over arrays?
We use the .each method
numbers = [1, 2, 3, 4, 5]
numbers.each { |element| puts element }
How do you iterate over multidimensional arrays?
s.each do | sub_array | sub_array.each do | y | puts y end end
How do you iterate over a hash?
As the same as in an Array, but you need to have two arguments instead of one.
restaurant_menu.each do | item, price |
puts “#{item}: #{price}”
end
What is a ‘Histogram’?
A visual representation of data is called a histogram.
What is a method?
A method is a reusable section of code written to perform a specific task in a program.
Why do we use methods?
- Easy to fix bugs
2. We use separation of concerns
How do you define a method?
You use the def syntax along with end
What is the structure of a method?
def method_name the_method_body
end
What is calling a method/function?
We call a method or a function when we want to use it.
What is a NameError?
You get a NameError when your program can’t find the method.
What is an argument?
The argument is the piece of code you actually put between the method’s parentheses when you call it
What is a parameter?
parameter is the name you put between the method’s parentheses when you define it.
What are splat arguments?
Splat arguments are arguments preceded by a *, which tells the program that the method can receive one or more arguments.
What is return?
When we want to get back a a value from the method instead of printing it to the console.
What are blocks?
Blocks are nameless methods.
Blocks can be defined with either the keywords do and end or with curly braces ( { } ).
They are only called once
Why do we use code blocks?
Because we want to use abstraction, which is basically making the code simpler.
What is a combined comparison operator?
The combined comparison operator is used to compare two ruby objects
what are hashes?
hashes are collections of key-value pairs
What happens when you try to access a key that doesn’t exist?
You will get the value nil
What does nil mean?
nil is Ruby’s way of saying “nothing at all.”
How do you set a new default value in a hash?
my_hash = Hash.new(“Trady Blix”)
Now if you try to access a nonexistent key in my_hash, you’ll get “Trady Blix” as a result.
What are symbols?
Symbols are not strings and can only be used once. They are used for referencing method names and as hash keys.
How do you write a symbol?
You write it:
:symbol_name
Why are symbols good as hash keys?
- They cant be changed once they are created (immutable)
- Only one symbol with the same name can exist so they save memory
- Symbols are faster.
How do you convert between strings and symbols?
with
.to_s (symbol to string)
.to_sym (string to symbol)
.intern (string to symbol)
How do you assign symbols as keys to a value?
You use the new syntax instead of the old hash syntax
new_hash = { one: 1, two: 2, three: 3 }
How can we filter values from a hash?
We use the .select method
How do we iterate over just a value?
With the .each_value method
How to we iterate over just a key?
With the .each_key method
How do you write a single line if statement?
puts “It’s true!” if true
How do you write a single line unless statement?
puts ‘Hello’ unless false
What is a ternary conditional expression?
A if/else statement is a ternary expression beacuse it takes three arguments:
- A boolean
- a expression to evaluate if the boolean is true
- a expression to evaluate if the boolean is false
boolean ? Do this if true: Do this if false
What is a case statement?
A case statement is a if/else statement that is used when there are a lot of conditions to check.
case language when "JS" then put "Websites!" when "Python" then puts "Science!" when "Ruby" then puts "Web apps!" else puts "I don't know!" end
What is a conditional assignment?
A conditional assignment assigns a variable to a name if the name is nil
favorite_animal = ‘cat’
favorite_animal | |= ‘dog’
print favorite_animal => cat
favorite_animal = nil
favorite_animal | |= ‘dog’
print favorite_animal => ‘dog’
What is a implicit return?
It means that ruby will return a value even though you did not require it.
What is a short-circuit evaluation?
It means in a conditional statement with two conditions the second condition is evaluated only when the first condition is not enough to determine the value of expression
false && true
What is the concatenation operator?
It is «
and used to push in a element to the end of an array or a string.
[1, 2, 3] «_space;4 => [1, 2, 3, 4]
‘Faraz ‘ «_space;‘Naeem’ => ‘Faraz Naeem’
What is string interpolation?
{ x } its when you add a value to a string, no need to convert it.
What is refactoring?
Refactoring means that one should make the code simpler and more readable whitout changing its properties or function
What is a ruby block?
A block is a bit of code that can be executed
You can use do …end or { } brackets
What is the collect method?
The collect method takes a block and applies the expression in the block to every element in an array
my_nums = [1, 2, 3] my_nums.collect { |num| num ** 2 } # ==> [1, 4, 9]
What is the yield keyword?
The yield keyword, when used inside the body of a method will allow you to call that method with a block of code and pass the torch or yield to that block.
Think of the yield keyword as stop executing the code in this method, go and instead execute the code in this block. Then return to the code in the method.
Are blocks objects?
No blocks are not objects and can therefore not be saved to a variable.
What are Procs?
Procs are saved blocks that you can name and turn into a method.
What are Procs used for?
Procs are used for keeping the code dry.
What is Dry
A programming concept : Don’t Repeat Yourself.
How do you create a Proc?
with Proc.new
cube = Proc.new { |x| x ** 3 }
What are the advantages of Procs?
1) They are objects
2) They can be reused.
How can you call on a Proc?
By using the .call method
How do you convert a symbol into a Proc?
with the & symbol.
How do you write a lambda?
lambda { | param | block }
What is the difference between lambdas and procs?
Lambda checks the number of arguments.
Lambdas count the arguments.
A lambda passes control back to the calling method.
Procs do not count the argument passed to them it just ignores needless arguments.
When are Curly braces required in ruby?
When you want to put the code in one single line.
Why would you like to use a Proc instead of a regular Method?
- Gives more flexibility
- you can store more in a variable
- required in the database syntax
What are attributes?
Attributes are specific properties of an object.
"Matz".length # ==> 4 Matz is an object .lenght is a method 4 is an attribute
What is a class?
A class is a way to organize and produce objects with similar attributes and methods.
Basically a blueprint.
How do you write a class?
class ClassName # some code
end
You use CamelCase for the class name
What is the initialize method?
The initialize method is used to boost up the class, it gives us attributes that we can start up with.
It will run every time we create the class.
What is an instance variable?
An instance variable makes the variable available in other parts of the application
What is scope of a variable?
The scope of a variable is where the variable is accessible for the rest of the program. Some variables are not accessible to other parts of the program.
What are global variables?
Variables that are available everywhere
What are local variables?
Variables that are only available inside certain methods.
How do you write instance variables?
you write them with a @
@variable_name
How do you write class variables?
You write them with two @@
@@variable_nameHow do yo wr
How do you write global variables?
1) You just define the variable outside the method or class.
2) If you are writing the global variable from inside a method or a class just write $ before the variable.
How should you create variables?
You should only create them with a limited scope so that they can only be changed from a few places.
What is inheritance?
inheritance is the process by which one class takes on the attributes and methods of another.
What is the inheritance syntax?
you use the < symbol to show the inheritance.
class DerivedClass < BaseClass # Some stuff! end
This means that DerivedClass inherits from BaseClass.
What is override?
If you want a class to not to take the attributes of the baseclass
What is the super keyword?
The super keyword is used when you want to accesses the attributes or the methods of a superclass
How do you set up a class in ruby?
class SomeClassName end
What is inheritance?
Inheritance means that a class has access to all methods and behaviors of another class. You use the < to show the inheritance.
What can you store in a class in ruby?
You can store both methods and data in a class.
What is the getter method in a class?
The getter method allows you to retrieve data or values from a class.
What is the setter method in a class?
The setter method allows you to set values in a class.
What is the attr_accessor?
The attr_accsessor stands for attribute accessor and is used instead of the getter and setter methods.
What does instantiation mean?
When you create a class it’s like creating a blueprint, to instantiate a class means to build the house from a blueprint. To actually use the class to create.
What is an initializer method?
An initializer method is a method that will run every time you create a new instance of a class.
What are optional values?
When you are not sure that you want to pass on a value as an argument, you can assign the value to be optional. It will only be assigned if you give an argument.
You write value = something if you want it to be optional
Why do we use inheritance in ruby?
We use inheritance because repeating code is a bad practice.
We use inheritance because repeating code is a bad practice.
It is when you use third-party services instead of creating your own.
What is a public method?
A public method is a method inside a class that can be used by anyone working with that perticular class. These are really important if you are giving access to these methods via an API.
What are private methods?
Private methods are methods that can only be called from whitin the class and not by an external service or user.
How do you make a method private?
You add the keyword private to a section of your class, and all methods that are added below that keyword will be private.
Ex class Example
def method_1
some_code
end
private
def method_2
some_code
end
end
What is polymorphism in ruby?
Polymorphism is when the behavior from the parent class is overridden by the child class.
How do you use Polymorphism?
You use it by defining a new class with the same method name, the method of the child class will be run instead of the method from the parent class.
What is the super keyword and when do you use it?
The super keyword allows us to use both methods from parent and child classes instead of polymorphism.
You use it by adding the keyword inside the method you want the parent class to override
What is the single responsibility principle?
It means that each class and module in the application should only focus on a single task.
Why are private methods used?
To make sure external users can’t access or harm your software.
What do private methods do?
They make sure that the method can’t be called from outside the class.
What is a public method?
A public method is a method that can be called from outside the class. All methods are public by default in ruby.
What is the attr_reader used for?
It is used for accessing a variable in a method/class
what is the attr_writer used for?
It’s used for changing the variable in the method/class
What is the attr_accessor used for?
It is used as bot a attr_reader and attr_writer.
What is an module in Ruby?
A module is like a class, but it can’t create instances or have subclasses.
Modules are good when using constants, because constants don’t change, but variables do.
How do you write a module?
module ModuleName # Bits 'n pieces
end
How do you write constants in ruby?
You write them in ALL_CAPS
like PI
What is namespacing?
The main purpose of a module is to separate methods and constants into named spaces, and this is called namespacing.
What is the scope resolution operator?
It is used for telling ruby where to look for something.
Math : : PI means that Ruby should look for the PI inside the Math module.
What is require?
When the interpreter doesn’t have a module you need to bring it in with require. It basically runs another file.
require ‘module’
What is include?
The include method takes all the methods from one module and includes them in the current method.
What is mixin?
Mixin is when you blend additional behaviour from a module into a class. Meaning that we can customise a class whit out writing new code.
What is the extend keyword?
The extend keyword means that the class can use the methods as opposed to the instance of the class.
How to delete a element from the end of an array?
arr = [1, 2, 3]
arr.pop
=> arr = [1, 2]
POP!!!
How to delete an element from the beginning of the array
arr = [1, 2, 3]
arr.shift
=> arr = [ 2, 3 ]
(Will return the value that was deleted in the terminal)
How to Delete an element at a given position
arr = [1, 2, 3]
arr.delete_at(1)
=> arr = [ 1, 3 ]
How to Delete all occurrences of a given element
arr = [1, 2, 3, 5, 6, 8, 5]
arr.delete(5)
=> [1, 2, 3, 6, 8]
How to select elements that satisfy a given criteria?
arr = [ 3, 4, 2, 1, 2, 3, 4, 5, 6]
arr.select {|a| a > 2}
[3, 4, 3, 4, 5, 6]
What is non destructive selection?
It is when the arrays remain unchanged after the selection.
How do you permanently delete objects in an array?
you use the delete_if method
arr.delete_if { | a | a < value }
How do you keep some of the objects in an array?
You use the .keep_if method
arr.keep_if {|a| a < value }
What is a splat operator?
A Splat operator gives us the method to insert multiple arguments, without predefining them.
What is a keyword based splat argument?
It is a mix between a keyword argument and a splat arguments.
What are optional arguments?
Optional arguments allows you to pass in any kind of arguments and then utilize them. They can lead to misleading bugs.
With what methods can you print to the ruby console?
Using puts, print, and p
What is the puts method?
The puts method will return a value to you and display it by printing each object in a new line. The puts method iterates through the objects and displays individual values.
What is the p method?
The p method will print the object in its code form.
What is the print method?
The print method will return a value to you and display it by printing each object. The print method iterates through the objects and displays individual values.
How do you get user input from the user?
With gets and chomp methods.
What is the gets method?
the gets method will prompt the user to give a input, it will however add a /n to the string or integer.
What is the .chomp method?
The .chomp method gets rid of the character: \n at the end of the line
What kind of variables are there?
- Local variables
- Global variables
- instance variables
- Constants
- Class variables
What is a local variable?
A local variable is a variable that is declared inside a method or a loop. The scope is that it is limited to only that method or loop
Undefined local variable or method
What is a global variable?
A global variables is a variable that is available for the entire application everywhere you write it with a $ before the variable name. Not a good idea to use them because they are hard to keep track of.
What is an instance variable?
An instance variable (@variable_name) is only available in during a particular occurance and it is not available in other methods.
Why not make it a local variable? Beacuse we want to call the method in other files, for that to happen we need to use an instance variable .
Ex view and controller.
What is an constant?
Generally constants are values that do not change.
You use all capital letters when declaring constants like PI = 3,14
Ruby does allow you to change a constant but it is poor programming practice to change constants.
What is a class variable?
Class variables ($$variable_name) are variables that are only used in a specific class. They are rarely used in practical situations.
What is a string?
A string is a data type which contains a set of characters, often a word or sentence. They need to be wrapped inside quotation marks
What is string interpolation?
It is the ability to integrate dynamic values inside a string. They are enclosed with a #{ } you can even run code you want to display inside the brackets. But it is not recommended to type entire methods with string interpolation.
What is string manipulation?
String manipulation is to alter the format or the value of a string.
Methods like upcase, downcase is used.
What is method chaining?
It is when we join multiple methods and use them.
What is string substititon
It is when you change a value in the string. We use the gsub method. which stands for global substitution
Why does one add a bang?
Adding a bang permenantly changes the the object with the changes.
What is the strip method?
The strip method takes away the spaces in the beginning and the end of a string.
What is the split method?
The split method takes a string and turns it into an array
What is a While loop?
While something is true the code will run, there is a danger of infinite loops in these cases, make sure to add a increment.
Ex i= i+1
What is the each loop?
The each loop is an iterator
that goes through an object and executes the code on each single object.
What is the one line each iterator?
arr.each { | x | do_something x }
What is the syntax for the each iterator?
arr.each do |x|
do_something x
end
What are nested iterators?
nested iterators are used when you want to extract and operate on hashes and arrays with multiple objects.
What is the select method in ruby?
The select method is a method that automatically iterates through a collection and retrieves the value you want.
How do you use the select method in ruby?
There are three ways to use the select method in ruby:
- something.select do |x|
some_code
end”
- something.select { |x| x.some_code}
- something.select(&:some_code)
How can you create arrays?
How do you delete values from arrays?
With the delete method
array.delete(value)
How do you delete an element from an array using the index?
With the delete at method
array.delete_at(index_number)
How do you delete elements from array that fit into an criteria?
with the delete if method
array.delete_if { |x| some_code }
What is the join method?
The join method returns a string created by converting each element of the array to a string, separated by the given separator. If the separator is nil, it uses current $,. If both the separator and $, are nil, it uses empty string.
[ “a”, “b”, “c” ].join #=> “abc”
[ “a”, “b”, “c” ].join(“-“) #=> “a-b-c”
What is the pop method?
It allows you to delete the last element of an array
1) array.pop
What is the push method?
it allows you to add an element to end of an array
1) array.push(element)
2 array.push(element1, element2, element3)
What is an hash?
The hash is an key:value collection that can store values.
How do you create a new hash?
1) hash = { first_key: ‘first element’ , second_key: ‘second_element’ } (this is the modern way to make a hash)
2) hash = { ‘first_key’ => ‘first_element’ }
3) hash = { :fist_key => ‘first element’ }
How do you grab an element from an hash?
hash{:chosen_key]
How do you delete elements from a hash?
you use the delete method
hash.delete(:key)
How do you iterate over just a hash key?
With the each_key method
hash.each_key do |key|
some_code
end
How do you iterate over just a hash value?
With the each_value method
hash.each_value do |value|
some_code
end
How do you add to a hash?
hash[:key] = value
How do you invert the key and the values in a hash?
You use the .invert method
hash.invert
How do you merge two hashes?
With the .merge method
hash1.merge(hash_2)
How do we convert a hash into an array?
With the to_a method
hash_1.to_a
How do you view all keys in a hash?
With the .key method
hash_1.key
How do you view all values in a hash?
with the .value metod
hash_1.value
What are conditional statements?
Conditional statements are structures that run code if conditions are met.
What is an if statement?
An if statement is a structure that runs if the given statement is true, otherwise it runs the else statement.
if conditional [then] run some_code elsif conditional [then] run some_code else run some_code end
What is the unless conditional?
The unless conditional is a method that runs if the conditional is not true
What are compounded conditionals?
It is when you add multiple conditionals with
| | or &&
What is Enumerable?
Enumerable is a module that contains methods to traverse, search and sorting collections. It si added by default in the Array and Hash classes. But can be added to a class by including it.
What is the select method?
The select method picks out what you want and puts it into a new array.
big_orders = orders.select { | o | o >= 300 }
What is the reject method?
The reject method finds objects and puts it into a new array just like the select method. The difference is that it rejects all objects that does match the criteria.
What is the any? method?
The any? method searches for a object inside a collection that matches a criteria, The execution stops once the object is found and return true.
What is the detect method?
The detect method searches for a object inside a collection that matches a criteria, The execution stops once the object is found and returns the first object it found.
What is the reduce method?
The reduce method is used to reduce a list down to a single value by combining objects.
[1, 2, 3].reduce(0) { |sum, n| sum + n } # => 6
0 is the initial value
What is the map method?
The method is used to map (transform) the elements in one array into another new array
[1, 2, 3].map { |n| n * 2 } # => [2, 4, 6]
What is the partion method?
The partition method is used to separate a collection into multiple parts giving you an array of arrays.
collection = [1, 2, 3, 4, 5, 6]
even, uneven = collection.partition {|v| v.even? }
even => [2, 4, 6]
uneven => [1, 3, 5]
How do you create a block method?
by defining a method that includes yield, and using the method to call a block.
How can you create your own iterator method?
By opening up the class and adding the method to it. You have to use self if you want to add the object to the front instead of passing it as a parameter