Ruby basics + advanced Flashcards

1
Q

What is ruby?

A

It is a programming language

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

What does RVM stand for?

A

Ruby version manager

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

What does RVM let you do?

A

It lets you switch between different versions of ruby.

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

What are variables?

A

They are the building blocks of a program and they let you store information.

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

How much information can a variable store?

A

Variables can store a lot of data, full algoritms, blocks and lambdas

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

How do you set a variable in ruby?

A

you give it a name and set it equal to the information

ex variable_1 = ‘A string’

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

How can you print out objects to the terminal?

A
  • puts
  • p
  • print
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is puts?

A

puts will return nil and print out the object in a new line. Puts also iterates over the values.

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

What is p?

A

p will return the value and print out the object

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

How do you get user input form the terminal?

A

you use the gets method

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

What is chomp?

A

chomp deletes the extra character that your gets method adds to the input.

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

What kinds of variables are there?

A
  • Local variables
  • Global variables
  • Instance variables
  • Constants
  • Class variables
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is a local variable?

A

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

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

What is a global variable?

A

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.

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

What is a instance variable?

A

An instance variable is written with a @ sign before the variable name.
The instance variable is available for that instance in other places.

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

What is a constant?

A

A constant is a variable is written with CAPITAL letters and is a variable that is not supposed to be changed.

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

What is a class variable?

A

A class variable is written with @@ is a variable that is available to that instance of the class.

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

What is a string?

A

A string is a object where you store a collection of characters. These must be contained in single or double quotes

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

What is string interpolation?

A

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.

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

What is string manipulation?

A

String manipulation is when you use methods to change the strings.

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

what is a bang? ( ! )

A

When you see the ! in the end of a method it means that it is changing the original version of the variable .

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

What is string substitution?

A

String substitution is a method in ruby. You use .gsub!( ‘original’ , ‘the change’)

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

What is the strip method?

A

it removes the extra spaces in a string in the beginning and in the end of a string

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

What is the split method?

A

The split method converts each word in a string to an array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What is the order of execution in ruby?
Please Excuse My Dear Aunt Sally = | Paranthesis, Exponents, Multiplication, Division, Addition, Subtraction
26
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.
27
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.
28
How do you declare a method?
def snake_case some logic end
29
How do you call/run a method?
you just type the method name
30
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.
31
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
32
How do you write a class method?
you add self before the method name in a class method. def self.method_name something end
33
How do you call a class with a class method
SomeClass.some_class_method
34
What are Procs?
Procs are blocks of code (methods) that can be stored inside variables.
35
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 ```
36
How do you call a Proc?
proc_variable[ argument1, argument2] or proc_variable.call(argument1, argument2)
37
How do write a lambda?
variable = lambda { |argument1, argument2 | some code } or variable = -> (argument1, argument2) { |argument1, argument2 | some code }
38
How do you call a lambda?
lambda_variable[ argument1, argument2] or lambda_variable.call(argument1, argument2)
39
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
40
What are method arguments?
The method arguments are the raw material provided by the user.
41
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")
42
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.
43
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 ...)
44
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)
45
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
46
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
47
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}
48
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
49
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 ```
50
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?)
51
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)
52
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(&:*) ```
53
How do you create an array?
ex x = [1, 2, 34 ] ex y = Array.new y[0] = 543
54
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 }
55
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"
56
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]
57
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]
58
How do you add an element to an array=
You add them by push or by index ex array[index] = value
59
What is a hash?
A hash is an key value collection (also called dictionary)
60
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}
61
How do you return a value from an hash based on a key?
hash[:key]
62
How do you delete an element from an hash?
with the delete method ex hash.delete(:key)
63
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
64
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
65
How do you add to a hash?
hash[:key] = value
66
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}
67
How do you merge two hashes?
with the merge method ex hash.merge(another_hash)
68
How do you convert a hash to an array
hash.to_a
69
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
70
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
71
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
72
How do you set up a class in ruby?
``` ex class ClassName ``` end everything within the class will belong to the class
73
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
74
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.
75
How many responsibilities should a class have?
only one
76
What is a public method?
It means that the method is visible to others.
77
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.
78
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.
79
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.
80
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 ```
81
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.
82
How do you delete a file?
ex | File.delete("file path")
83
How do you update a file in ruby?
ex ( will add stuff to the file) | File.open("file path" "a") {|f| some_code}
84
What is the basic syntax for error handling in ruby? | not using Rspec
``` ex begin some code rescue some code end ```
85
How should you write errors in ruby? (not using Rspec)
``` ex begin some code rescue StandarError => variable puts "error message #{variable}" end ```
86
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.
87
what is the basic syntax for regular expressions?
=~ /matcher/
88
What is grep?
Grep is a method that is used to search through collections and objects. ex array.grep(search_object)
89
What are ruby gems?
Ruby gems are basically ruby code packaged.
90
What is metaprogramming in ruby?
It is the process of writing code that writes itself during runtime.
91
What is the w%( ) method?
it allows you to create an array from a string without adding commas and such.
92
What is the freeze method?
The freeze method makes an object unable to change.
93
How do you interact with an API with ruby?
You need a gem (httparty) to interact and you also need a class with methods.
94
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),
95
Do you need to use a web framework like Rails or Sinatra to work with APIs?
No
96
What is a popular gem for working with APIs?
httparty
97
What type of data is typically sent back as an API response?
JSON
98
What is the sort method?
The sort method allows you to sort the elements inside an array.
99
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. ```
100
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.
101
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.
102
What is the & prefix?
the & prefix allows us to pass in a code block as a parameter like { print 'Ho!' }
103
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
104
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. ```
105
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
106
What arithmetic operator are there in ruby?
addition + subtraction - multiplication * division / modulo % exponentiation **
107
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.
108
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.
109
What is an interpreter?
An interpreter is a program that takes your code and runs it, it shows the result in your console
110
How do you use a method?
Methods are used with a . | my_string = 'i love pizza' --> my_string.length --> 12
111
How do write a comment in ruby?
you use # | Everything behind the (on the same line) # will be commented out
112
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.
113
What is a naming convention?
A naming convention is how the community writes code, local variables should be written in lowercase letters and words.
114
How do you declare or set a variable?
You use the = | my_number = 12
115
How can you call multiple methods on a variable?
by chaining | name.method1.method2.method3
116
What is chaining?
Chaining is that you call multiple methods on a variable
117
What is control flow?
Control flow is that we can select different outcomes depending on the environment and the input.
118
What is an if statement?
Ruby takes an if statement and decides if its true and runs code accordingly.
119
What is an else statement?
The else statement is the continuation of the if statement. This code runs after the if statement is false.
120
What is an elsif statement?
An elsif statement gives the if else statement more options.
121
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.
122
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.
123
What are the comparator for less or equal than?
less than < less than or equal to <= greater than > Greater than or equal to >=
124
What are boolean operators?
Boolean operators are either true or false - && (and) - | | (or) - ! (not)
125
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
126
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
127
What is an Not-operator?
A not operator (!) makes any statement after the expression false !true= false
128
What is gets.chomp?
Gets chomp is for getting user input from the terminal
129
What is the .downcase method?
the .downcase method takes the user input and converts it do lower case letters.
130
What is the .include? method
The include? method checks if the user input contains what we want
131
What is the .gsub! method?
The .gsub method stands for global substitution and changes all the chosen inputs. string_to_change.gsub!(/s/, "th")
132
What is string interpolation ?
String interpolation adds a value to a string. | print "Adios, #{my_string}!"
133
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 ```
134
What is an infinite loop?
An infinite loop is a loop that runs forever. | They need to be avoided at all cost.
135
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 ```
136
What is an assignment operator?
An assignment operator is used to update a variable. | +=, -=, *=, and /=.
137
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
138
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
139
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
140
What is an iterator?
An iterator is just a Ruby method that repeatedly invokes a block of code.
141
What is the next keyword?
The next keyword is used to skip a step.
142
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.
143
How do you get user input?
gets.chomp
144
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 ```
145
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!" }
146
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(",")
147
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.
148
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
149
What are multidimensional arrays?
It's an array of arrays
150
What are hashes?
A hash is a collection of key-value pairs
151
How do you create a hash?
You use the Hash.new method. by setting a variable to Hash.new my_hash = Hash.new
152
How do you add objects to a hash?
We add object to hash with bracket notation: ``` pets = Hash.new pets["Stevie"] = "cat" ```
153
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"]
154
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.
155
How do we iterate over arrays?
We use the .each method numbers = [1, 2, 3, 4, 5] numbers.each { |element| puts element }
156
How do you iterate over multidimensional arrays?
``` s.each do | sub_array | sub_array.each do | y | puts y end end ```
157
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
158
What is a 'Histogram'?
A visual representation of data is called a histogram.
159
What is a method?
A method is a reusable section of code written to perform a specific task in a program.
160
Why do we use methods?
1. Easy to fix bugs | 2. We use separation of concerns
161
How do you define a method?
You use the def syntax along with end
162
What is the structure of a method?
``` def method_name the_method_body ``` end
163
What is calling a method/function?
We call a method or a function when we want to use it.
164
What is a NameError?
You get a NameError when your program can't find the method.
165
What is an argument?
The argument is the piece of code you actually put between the method's parentheses when you call it
166
What is a parameter?
parameter is the name you put between the method's parentheses when you define it.
167
What are splat arguments?
Splat arguments are arguments preceded by a *, which tells the program that the method can receive one or more arguments.
168
What is return?
When we want to get back a a value from the method instead of printing it to the console.
169
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
170
Why do we use code blocks?
Because we want to use abstraction, which is basically making the code simpler.
171
What is a combined comparison operator?
The combined comparison operator is used to compare two ruby objects
172
what are hashes?
hashes are collections of key-value pairs
173
What happens when you try to access a key that doesn't exist?
You will get the value nil
174
What does nil mean?
nil is Ruby's way of saying "nothing at all."
175
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.
176
What are symbols?
Symbols are not strings and can only be used once. They are used for referencing method names and as hash keys.
177
How do you write a symbol?
You write it: | :symbol_name
178
Why are symbols good as hash keys?
1. They cant be changed once they are created (immutable) 2. Only one symbol with the same name can exist so they save memory 3. Symbols are faster.
179
How do you convert between strings and symbols?
with .to_s (symbol to string) .to_sym (string to symbol) .intern (string to symbol)
180
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 } ```
181
How can we filter values from a hash?
We use the .select method
182
How do we iterate over just a value?
With the .each_value method
183
How to we iterate over just a key?
With the .each_key method
184
How do you write a single line if statement?
puts "It's true!" if true
185
How do you write a single line unless statement?
puts 'Hello' unless false
186
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
187
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 ```
188
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'
189
What is a implicit return?
It means that ruby will return a value even though you did not require it.
190
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
191
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] << 4 => [1, 2, 3, 4] 'Faraz ' << 'Naeem' => 'Faraz Naeem'
192
What is string interpolation?
#{ x } its when you add a value to a string, no need to convert it.
193
What is refactoring?
Refactoring means that one should make the code simpler and more readable whitout changing its properties or function
194
What is a ruby block?
A block is a bit of code that can be executed | You can use do ...end or { } brackets
195
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] ```
196
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.
197
Are blocks objects?
No blocks are not objects and can therefore not be saved to a variable.
198
What are Procs?
Procs are saved blocks that you can name and turn into a method.
199
What are Procs used for?
Procs are used for keeping the code dry.
200
What is Dry
A programming concept : Don't Repeat Yourself.
201
How do you create a Proc?
with Proc.new | cube = Proc.new { |x| x ** 3 }
202
What are the advantages of Procs?
1) They are objects | 2) They can be reused.
203
How can you call on a Proc?
By using the .call method
204
How do you convert a symbol into a Proc?
with the & symbol.
205
How do you write a lambda?
lambda { | param | block }
206
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.
207
When are Curly braces required in ruby?
When you want to put the code in one single line.
208
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
209
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 ```
210
What is a class?
A class is a way to organize and produce objects with similar attributes and methods. Basically a blueprint.
211
How do you write a class?
``` class ClassName # some code ``` end You use CamelCase for the class name
212
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.
213
What is an instance variable?
An instance variable makes the variable available in other parts of the application
214
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.
215
What are global variables?
Variables that are available everywhere
216
What are local variables?
Variables that are only available inside certain methods.
217
How do you write instance variables?
you write them with a @ | @variable_name
218
How do you write class variables?
You write them with two @@ | @@variable_nameHow do yo wr
219
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.
220
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.
221
What is inheritance?
inheritance is the process by which one class takes on the attributes and methods of another.
222
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.
223
What is override?
If you want a class to not to take the attributes of the baseclass
224
What is the super keyword?
The super keyword is used when you want to accesses the attributes or the methods of a superclass
225
How do you set up a class in ruby?
``` class SomeClassName end ```
226
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.
227
What can you store in a class in ruby?
You can store both methods and data in a class.
228
What is the getter method in a class?
The getter method allows you to retrieve data or values from a class.
229
What is the setter method in a class?
The setter method allows you to set values in a class.
230
What is the attr_accessor?
The attr_accsessor stands for attribute accessor and is used instead of the getter and setter methods.
231
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.
232
What is an initializer method?
An initializer method is a method that will run every time you create a new instance of a class.
233
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
234
Why do we use inheritance in ruby?
We use inheritance because repeating code is a bad practice.
235
We use inheritance because repeating code is a bad practice.
It is when you use third-party services instead of creating your own.
236
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. ```
237
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.
238
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
239
What is polymorphism in ruby?
Polymorphism is when the behavior from the parent class is overridden by the child class.
240
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.
241
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
242
What is the single responsibility principle?
It means that each class and module in the application should only focus on a single task.
243
Why are private methods used?
To make sure external users can't access or harm your software.
244
What do private methods do?
They make sure that the method can't be called from outside the class.
245
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.
246
What is the attr_reader used for?
It is used for accessing a variable in a method/class
247
what is the attr_writer used for?
It's used for changing the variable in the method/class
248
What is the attr_accessor used for?
It is used as bot a attr_reader and attr_writer.
249
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.
250
How do you write a module?
``` module ModuleName # Bits 'n pieces ``` end
251
How do you write constants in ruby?
You write them in ALL_CAPS | like PI
252
What is namespacing?
The main purpose of a module is to separate methods and constants into named spaces, and this is called namespacing.
253
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.
254
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'
255
What is include?
The include method takes all the methods from one module and includes them in the current method.
256
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.
257
What is the extend keyword?
The extend keyword means that the class can use the methods as opposed to the instance of the class.
258
How to delete a element from the end of an array?
arr = [1, 2, 3] arr.pop => arr = [1, 2] POP!!!
259
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)
260
How to Delete an element at a given position
arr = [1, 2, 3] arr.delete_at(1) => arr = [ 1, 3 ]
261
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]
262
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]
263
What is non destructive selection?
It is when the arrays remain unchanged after the selection.
264
How do you permanently delete objects in an array?
you use the delete_if method | arr.delete_if { | a | a < value }
265
How do you keep some of the objects in an array?
You use the .keep_if method | arr.keep_if {|a| a < value }
266
What is a splat operator?
A Splat operator gives us the method to insert multiple arguments, without predefining them.
267
What is a keyword based splat argument?
It is a mix between a keyword argument and a splat arguments.
268
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.
269
With what methods can you print to the ruby console?
Using puts, print, and p
270
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.
271
What is the p method?
The p method will print the object in its code form.
272
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.
273
How do you get user input from the user?
With gets and chomp methods.
274
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.
275
What is the .chomp method?
The .chomp method gets rid of the character: \n at the end of the line
276
What kind of variables are there?
- Local variables - Global variables - instance variables - Constants - Class variables
277
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
278
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.
279
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.
280
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.
281
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.
282
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
283
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.
284
What is string manipulation?
String manipulation is to alter the format or the value of a string. Methods like upcase, downcase is used.
285
What is method chaining?
It is when we join multiple methods and use them.
286
What is string substititon
It is when you change a value in the string. We use the gsub method. which stands for global substitution
287
Why does one add a bang?
Adding a bang permenantly changes the the object with the changes.
288
What is the strip method?
The strip method takes away the spaces in the beginning and the end of a string.
289
What is the split method?
The split method takes a string and turns it into an array
290
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
291
What is the each loop?
The each loop is an iterator | that goes through an object and executes the code on each single object.
292
What is the one line each iterator?
arr.each { | x | do_something x }
293
What is the syntax for the each iterator?
arr.each do |x| do_something x end
294
What are nested iterators?
nested iterators are used when you want to extract and operate on hashes and arrays with multiple objects.
295
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.
296
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)
297
How can you create arrays?
1) variable = [1, 2, 3] 2) variable = Array.new then add elements by id number y[0] = 543 3) nums = Array.[](1, 2, 3, 4,5) 4) nums = Array[1, 2, 3, 4,5] 5) array = %w{ a b c d }
298
How do you delete values from arrays?
With the delete method | array.delete(value)
299
How do you delete an element from an array using the index?
With the delete at method | array.delete_at(index_number)
300
How do you delete elements from array that fit into an criteria?
with the delete if method | array.delete_if { |x| some_code }
301
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"
302
What is the pop method?
It allows you to delete the last element of an array | 1) array.pop
303
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)
304
What is an hash?
The hash is an key:value collection that can store values.
305
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' }
306
How do you grab an element from an hash?
hash{:chosen_key]
307
How do you delete elements from a hash?
you use the delete method | hash.delete(:key)
308
How do you iterate over just a hash key?
With the each_key method hash.each_key do |key| some_code end
309
How do you iterate over just a hash value?
With the each_value method hash.each_value do |value| some_code end
310
How do you add to a hash?
hash[:key] = value
311
How do you invert the key and the values in a hash?
You use the .invert method | hash.invert
312
How do you merge two hashes?
With the .merge method | hash1.merge(hash_2)
313
How do we convert a hash into an array?
With the to_a method | hash_1.to_a
314
How do you view all keys in a hash?
With the .key method | hash_1.key
315
How do you view all values in a hash?
with the .value metod | hash_1.value
316
What are conditional statements?
Conditional statements are structures that run code if conditions are met.
317
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 ```
318
What is the unless conditional?
The unless conditional is a method that runs if the conditional is not true
319
What are compounded conditionals?
It is when you add multiple conditionals with | | | or &&
320
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.
321
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 }
322
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.
323
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.
324
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.
325
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
326
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]
327
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]
328
How do you create a block method?
by defining a method that includes yield, and using the method to call a block.
329
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