Ruby basics Flashcards

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

How do you declare a class name?

A

When naming your classes you will use CamelCase formatting. CamelCase uses no spaces and capitalizes every word.

  # Class naming
  class MyFirstClass
  end
  class MySecondClass
  end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What do you use when the entire expression fits on one line in a do/end block?

A

Use { }

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

What does namespace mean and do

A

he :: symbol is used to define a namespace, which is just a way to group classes in Ruby and differentiate from other classes with the same name. For example ActiveRecord::Base is referring to the Base class in the ActiveRecord module, to differentiate from other classes also named Base.

However, when looking at the method list on the side bar, the :: means something different: it means that the method after the :: is a class method

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

What are methods denoted by :: in documentation

A

class methods

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

What are methods denoted by # in documentation

A

instance methods

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

How do we express nothing in programming

A

By using the value nil

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

How do you check if something has a nil value?

A

.nil?

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

How is nil treated in an if statement?

A

Treated as FALSE, as it represents an absence of content

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

What does => nil mean when your run puts “test”

A

It means that you have no return

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

a = puts “test”
puts a
What will be printed on the screen?

A

nil

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

What are variables

A

Variables are used to store information to be referenced and manipulated in a computer program.

They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves.

It is helpful to think of variables as containers that hold information.

Their sole purpose is to label and store data in memory. This data can then be used throughout your program.

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

Variable scope

A

Inner scope can access variables initialized in an outer scope, but not vice versa.

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

What’s the distinguishing factor for deciding whether code is a block?

arr = [1, 2, 3]

for i in arr do
a = 5 # a is initialized here
end

puts a # is it accessible here?

A

the key distinguishing factor for deciding whether code delimited by {} or do/end is considered a block (and thereby creates a new scope for variables), is seeing if the {} or do/end immediately follows a method invocation

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

Is for do..end creating an inner scope? Why is that useful?

A

No

Variable created in the for will be accessible outside of it as it will be in the same scope.

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

How many types of variables are there?

A

5

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

Constant variables

A

Created with uppercased letters
Cannot be declared in a method’s definition
Can be changed in ruby, while in other languages not. Still, dont change them once declared

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

Global variables

A

created with $
are accessible everywhere in the app, overriding all scope boundaries
there can be complications when using them

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

Class variables

A
declared with @@
accessible by instances of my class and the class itself

Use when you need to create a variable related to the class and when instances of that class do not need their own value for that variable

Must be initialized at the class level

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

Instance variables

A

Declared with @

Available in the instance of the parent class

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

Why are parameters used in a method

A

Parameters are used when you have data outside of a method definition’s scope, but you need access to it within the method definition. If the method definition does not need access to any outside data, you do not need to define any parameters.

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

Default parameters

A

def say(words=’hello’)

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

Optional parentheses

A

For example, say() could be rewritten as just say. With arguments, instead of say(“hi”), it could just be say “hi”.

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

Method definition and local variable scope

A

A method definition creates its own scope outside the regular flow of execution. This is why local variables within a method definition cannot be referenced from outside of the method definition. It’s also the reason why local variables within a method definition cannot access data outside of the method definition (unless the data is passed in as a parameter).

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

Mutating caller methods

A

Methods that perform actions on the argument passed to a method which mutates the caller

a = [1, 2, 3]

Example of a method definition that modifies its argument permanently
def mutate(array)
array.pop
end

p “Before mutate method: #{a}”
mutate(a)
p “After mutate method: #{a}”

Pop mutates the caller

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

What is a conditional

A

a fork in the road.

our data approaches a conditional and the conditional then tells the data where to go based on some defined parameters.

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

How are conditionals formed?

A

Conditionals are formed using a combination of if statements and comparison operators (, <=, >=, ==, !=, &&, ||).

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

What’s the order of precedence?

A

Used when deciding how to evaluate multiple expressions. The following is a list of operations from highest order of precedence (top) to lowest (bottom).

<=, , >= - Comparison
==, != - Equality
&& - Logical AND
|| - Logical OR

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

Describe a case statement

A

Has similar functionality to an if statement but with a slightly different interface.

Case statements use the reserved words case, when, else, and end.

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

How do you loop?

A
loop do
//something
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

How do you skip the rest of the code in a loop and start with the next iteration?

A

By using next

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

How do you exit the loop immediately?

A

By using break

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

What is a while loop

A

A while loop is given a parameter that evaluates to a boolean (remember, that’s just true or false). Once that boolean expression becomes false, the while loop is not executed again, and the program continues after the while loop.

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

How to write a while loop

A

while boolean statement
do something
end

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

How to write an until loop

A

until boolean statement
do something
end

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

What’s an until loop

A

Opposite of while loop

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

What are the ways to use a do/while loop

A
loop do
do something
if this condition is true
break out of loop
end

begin
do something
end while condition

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

Difference between do while and while loops

A

Code in do while gets executed at least once

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

What are for loops used for?

A

for loops are used to loop over a collection of elements

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

What’s the difference between for loops and while loops

A

Unlike a while loop where if we’re not careful we can cause an infinite loop, for loops have a definite end since it’s looping over a finite number of elements

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

How do you write a for loop?

A

It begins with the for reserved word, followed by a variable, then the in reserved word, and then a collection of elements.

for i in 1..10 do
puts i
end

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

What is a range?

A

A range is a special type in Ruby that captures a range of elements. For example 1..3 is a range that captures the integers 1, 2, and 3.

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

What does a for loop return?

A

The collection of elements after it executes

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

What does a while loop return

A

nil

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

What method is used to decide if a number is not event?

A

odd?

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

What are iterators?

A

Iterators are methods that naturally loop over a given set of data and allow you to operate on each element in the collection.

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

What does each do?

A

loops through each elements of a collection and allows you to operate over each element

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

Explain how .each works

A

The block’s starting and ending points are defined by the curly braces {}. Each time we iterate over the array, we need to assign the value of the element to a variable. In this example we have named the variable name and placed it in between two pipes |. After that, we write the logic that we want to use to operate on the variable, which represents the current array element. In this case it is simply printing to the screen using puts.

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

What’s a block?

A

Lines of code ready to be executed, inside { } or a do..end

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

When do you use do…end

A

When performing multi-line operations

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

What is recursion

A

Another way to create a loop.

Recursion is the act of calling a method from within itself..

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

What does each_with_index do?

A

Iterates through a collection and makes available the index and the item for use

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

What does .pop do to an array?

A

removes last element in an array, and mutates the caller

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

What does “mutate the caller” mean?

A

permanently changes the caller

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

What is the caller?

A

the collection calling an instance method

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

What does push do?

A

adds an item to the end of an array

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

Shovel operator

A

&laquo_space;- adds item to end of array

mutates the caller

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

Map method

A

The map method iterates over an array applying a block to each element of the array and returns a new array with those results.

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

What’s the other name you can use for map?

A

collect

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

Do map or collect mutate the caller?

A

These methods are not destructive (i.e., they don’t mutate the caller).

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

How do you know which methods mutate the caller or not?

A

You have to use the methods and pay attention to the output in irb; that is, you have to memorize or know through using it.

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

Why would you use delete_at

A

Delete a value at a certain index

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

How would you delete a value at a certain index?

A

delete_at

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

What does delete do

A

Deletes all instances of a provided value in an array

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

How do you delete all instances of a value in an array

A

Use .delete(value)

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

What does uniq do?

A

Deletes all duplicates in an array , returning the results as a new array. It does not modify the initial array

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

How can you make the uniq method forcibly mutate the caller?

A

Use !

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

Are uniq and uniq! the same methods?

A

No, they are different methods, one returns a new array while the other mutates the caller

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

How do you filter an array in Ruby

A

use the select {bloc}

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

What does .select do?

A

This method iterates over an array and returns a new array that includes any items that return true to the expression provided.

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

Does .select mutate the caller?

A

It does not, it returns an array with the filtered elements

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

! exception

A

Not all methods are destructive/ mutates the caller. Check the documentation.

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

Example of methods which are destructive but don’t have !

A

push / pop

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

What does unshift do?

A

Adds the value provided to the front of the array.

It is the opposite of .pop

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

What does to_s do to an array?

A

creates the string representation of the array

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

What does include? do?

A

The include? method checks to see if the argument given is included in the array.

76
Q

What does the ? at the end of a method mean?

A

usually means that it will return a boolean value

77
Q

What does flatten do?

A

The flatten method can be used to take an array that contains nested arrays and create a one-dimensional array.

It does not mutate the caller, it is not destructive

78
Q

How do you create an one-dimensional array?

A

Use flatten

79
Q

What does each_index do?

A

The each_index method iterates through the array much like the each method, however the variable represents the index number as opposed to the value at each index.

80
Q

What does each_with_index do?

A

each_with_index gives us the ability to manipulate both the value and the index by passing in two parameters to the block of code. The first is the value and the second is the index

81
Q

What does the .sort method do?

A

Sorts the array

82
Q

Is sort method destructive?

A

Check the array

83
Q

What does .product do?

A

It returns an array that is a combination of all elements from all arrays.

84
Q

What’s the difference between each and map?

A

each provides a simple way of iterating over a collection in Ruby and is more preferred to using the for loop. The each method works on objects that allow for iteration and is commonly used along with a block. If given a block, each runs the code in the block once for each element in the collection and returns the collection it was invoked on. If no block is given, it returns an Enumerator

map also works on objects that allow for iteration. Like each, when given a block it invokes the given block once for each element in the collection. Where it really differs from each is the returned value. map creates and returns a new array containing the values returned by the block.

85
Q

What does each return?

A

the caller

86
Q

What does map return?

A

creates and returns an array with the modified values

87
Q

How does map work?

A

map also works on objects that allow for iteration. Like each, when given a block it invokes the given block once for each element in the collection. Where it really differs from each is the returned value. map creates and returns a new array containing the values returned by the block.

88
Q

How does each work?

A

each provides a simple way of iterating over a collection in Ruby and is more preferred to using the for loop. The each method works on objects that allow for iteration and is commonly used along with a block. If given a block, each runs the code in the block once for each element in the collection and returns the collection it was invoked on. If no block is given, it returns an Enumerator

89
Q

What does puts return?

A

nil

90
Q

What does map return if not block is given?

A

Enumerator

91
Q

What do you use each for?

A

Iterating through a collection

92
Q

What do you use map for?

A

Transforming a collection

93
Q

What is a hash

A

Data structure that stores items by associated keys

94
Q

What is the difference between a hash and an array

A

A hash stores item by associated keys, while an array stores them by index

95
Q

How are entries in a hash referred to?

A

Key-value pairs

96
Q

How is a hash created

A

Using symbols as key and data types as values

All key-value pairs in a hash are surrounded by { }, and separated by ,

97
Q

How do you create a hash?

A

The older syntax comes with a => sign to separate the key and the value.

old_syntax_hash = {:name => ‘bob’}

The newer syntax is introduced in Ruby version 1.9 and is much simpler. As you can see, the result is the same.

new_hash = {name: ‘bob’}

98
Q

How do you add to an existing hash?

A

person[:hair] = ‘brown’

99
Q

How do you remove something from a hash?

A

person.delete(:age)

100
Q

How do you retrieve a piece of info from a hash?

A

person[:weight]

101
Q

How do you merge 2 hashes?

A

person.merge!(new_hash)

102
Q

Why do you use the ! in the merge of 2 hashes?

A

This modifies the caller, instead of returning a separate merged array. It makes the modification on the spot

103
Q

How do you iterate over hashes?

A

Use the each method and assign a variable to both the key and the value of the hash

person = {name: ‘bob’, height: ‘6 ft’, weight: ‘160 lbs’, hair: ‘brown’}

person.each do |key, value|
puts “Bob’s #{key} is #{value}”
end

104
Q

Hashes as optional parameters

A

You can pass an empty hash as a default value to an parameter in a method.

You can use a hash to accept optional parameters when you are creating methods

def greeting(name, options = {})
  if options.empty?
    puts "Hi, my name is #{name}"
  else
    puts "Hi, my name is #{name} and I'm #{options[:age]}" +
         " years old and I live in #{options[:city]}."
  end
end

greeting(“Bob”)
greeting(“Bob”, {age: 62, city: “New York City”})

105
Q

What does .empty? do?

A

Detect whether a variable has anything passed into it

106
Q

What is the peculiarity of a hash in a def

A

if it is the last argument, the { } are not required when calling the method

107
Q

What to choose between an array and a hash?

A

When deciding whether to use a hash or an array, ask yourself a few questions:

Does this data need to be associated with a specific label? If yes, use a hash. If the data doesn’t have a natural label, then typically an array will work fine.

Does order matter? If yes, then use an array. As of Ruby 1.9, hashes also maintain order, but usually ordered items are stored in an array.

Do I need a “stack” or a “queue” structure? Arrays are good at mimicking simple “first-in-first-out” queues, or “last-in-first-out” stacks.

108
Q

What datatypes can you use as keys in a hash?

A

Those that are hashable, such as String, Int, Double etc

109
Q

What does has_key? do?

A

The has_key? method allows you to check if a hash contains a specific key. It returns a boolean value.

110
Q

What does select do in a hash?

A

The select method allows you to pass a block and will return any key-value pairs that evaluate to true when ran through the block.

111
Q

What does fetch do in a hash?

A

The fetch method allows you to pass a given key and it will return the value for that key if it exists.

You can also specify an optional return if the key is not present

112
Q

What does to_a do in a hash?

A

The to_a method returns an array version of your hash when called.

my_hash = {age: 12, name: “John”}
p my_hash.to_a.first.last

puts my_hash
p my_hash.to_a

113
Q

How do you retrieve all the keys only?

A

.keys

114
Q

How do you retrieve all the values only?

A

.values

115
Q

Create a file

A

File.new(“name”,”w+”)

.new method with 2 arguments (a name and the access on file)

116
Q

When should you close a file

A

When the opening doesnt happen in a block

117
Q

Why should you close files?

A

They continue occupying space in memory otherwise

118
Q

What does r do when opening a file?

A

read-only (starts at beginning of file)

119
Q

What does w do?

A

write-only (if the file exists, overwrites everything in the file)

120
Q

What does w+ do?

A

read and write (if the file exists, overwrites everything in the file)

121
Q

What does a+ do?

A

read-write (if file exists, starts at end of file. Otherwise creates a new file). Suitable for updating files.

122
Q

Open a file for reading

A

File.read(“file_name”) - Spits out entire contents of the file.

123
Q

What does File.readlines(“file_name”) do?

A

Reads the entire file based on individual lines and returns those lines in an array.

124
Q

Open file for writing

A

File.open(“name”,”w”) { | file | file.write(“new text”) }

Use write or puts to write to a file

125
Q

What should you do after this?

sample = File.open(“name”,”w+”)

sample.puts(“another text”)

A

sample.close

you need to close the file if the operation of writing happens outside a block

126
Q

What’s the other option for writing to a file

A

File.open(“filename”,”w+”) do | file |
file_name &laquo_space;“text”
end

127
Q

Delete a file

A

File.delete(“name”)

128
Q

What does the Pathname class do?

A

he Pathname class exposes pretty much all of the methods of File and Dir. The advantage to using Pathname is you can declare an instance of it and access the class methods of File and Dir on the instance object.

129
Q

What’s the Dir class?

A

Dir - Dir shares some of File’s methods. However, it is not an IO stream.

130
Q

What is REGEX

A

Regex stands for regular expression. A regular expression is a sequence of characters that form pattern matching rules, and is then applied to a string to look for matches.

131
Q

How do you create a regex

A

Creating regular expressions starts with the forward slash character (/). Inside two forward slashes you can place any characters you would like to match with the string.

/ /

132
Q

What is =~ used for

A

We can use the =~ operator to see if we have a match in our regular expression. Let’s say we are looking for the letter “b” in a string “powerball”. Here’s how we’d implement this using the =~ operator

irb :001 > “powerball” =~ /b/
=> 5

133
Q

What is the result of =~ useful for

A

We can use it as a boolean to check for matches.

def has_a_b?(string)
  if string =~ /b/
    puts "We have a match!"
  else
    puts "No match here."
  end
end

has_a_b?(“basketball”)

134
Q

Match method

A

Same as =~

135
Q

What does match return?

A

This method returns a MatchData object that describes the match or nil if there is no match.

136
Q

What is the result of match useful for?

A

You can use a MatchData object to act as a boolean value in your program:

def has_a_b?(string)
  if /b/.match(string)
    puts "We have a match!"
  else
    puts "No match here."
  end
end

has_a_b?(“basketball”)

137
Q

What are Ruby Standard Classes?

A

When you have a specific action that you need to perform, look for it first among Ruby’s standard classes.

138
Q

Example of Ruby Standard Classes?

A

Ruby’s Math module has a method called sqrt that you can use right away.

Math.sqrt(400) //20

Math::PI
=> 3.141592653589793

You can use Ruby's built-in Time class.
irb :003 > t = Time.new(2008, 7, 4)
=> 2008-07-04 00:00:00 -0400
irb :004 > t.monday?
=> false
irb :005 > t.friday?
=> true
139
Q

Variables as pointers?

A

Variables act as pointers to a place in memory

140
Q

What happens when you change the value of a variable?

A

When you change the value of a variable you re-assign it to a different physical place in memory. This is what = does.

141
Q

What happens when you assign the initial value back to a variable?

A

If you re-assign the initial value back, you are actually occupying a different space in memory, not the initial one

142
Q

What happens if you assign the same value to a different variable?

A

If you assign the variable to a different variable, you will have to different spaces in memory holding the same value

a = "hi there"
b = a
a = "not here"

Here, you are potingin to different spaces in memory for different values,

But if at the end you do a = “hi there” you will potin to 2 different places but have the same value in both

143
Q

Can you pass Blocks in methods as parameters?

A

Yes, as the last parameter

passing_block.rb

def take_block(&block)
block.call
end

take_block do
puts “Block being called in the method!”
end

The only difference is that when you call the take_block method you pass it a bloc via do…end

144
Q

What does the & in a method definition means?

A

Tells us that the argument is a block.

You put it in front of the argument in the definition

145
Q

How do you tell a method that the argument passed to it is a block?

A

&

146
Q

What are we doing here and what is the result?

def take_block(number, &block)
block.call(number)
end

number = 42
take_block(number) do |num|
puts “Block being called in the method! #{num}”
end

A

Here we are passing the number into the take_block method and using it in our block.call.

Define the take_block method which takes 2 parameters, a number and a block.

The block is called in the definition with the number being passed as a parameter. If you do not call the method with the number parameter the method will not work

147
Q

What are procs?

A

Procs are blocks that are wrapped in a proc object and stored in a variable to be passed around

148
Q

How do you define a proc?

A

proc_example.rb

talk = Proc.new do
puts “I am talking.”
end

talk.call

149
Q

Can procs take arguments? How?

A

Yes

proc_example.rb

talk = Proc.new do |name|
puts “I am talking to #{name}”
end

talk.call “Bob”

150
Q

Can procs be passed into methods? How?

A

passing_proc.rb

Yes

def take_proc(proc)
  [1, 2, 3, 4, 5].each do |number|
    proc.call number
  end
end

proc = Proc.new do |number|
puts “#{number}. Proc being called in the method!”
end

take_proc(proc)

151
Q

What is exception handling?

A

Exception handling is a specific process that deals with errors in a manageable and predictable way

152
Q

Why is exception handling needed?

A

When your programs are interacting with the real world, there is a large amount of unpredictablility. If a user enters bad information or a file-manipulating process gets corrupted, your program needs to know what to do when it runs into these exceptional conditions.

One common occurrence of this is when a nil value makes its way into our program.

153
Q

What’s the format of the exception handling and the reserved words

A

exception_example.rb

begin
  # perform some dangerous operation
rescue
  # do this if operation fails
  # for example, log the error
end
154
Q

How does the exception work?

A

When an exception, or error, is raised, the rescue block will execute and then the program will continue to run as it normally would. If we didn’t have the rescue block there, our program would stop once it hit the exception and we would lose the rest of our print-out.

155
Q

How else can you use the rescue word?

A

You can also use the rescue reserved word in-line like so:

inline_exception_example.rb

zero = 0
puts “Before each call”
zero.each { |element| puts element } rescue puts “Can’t do that!”
puts “After each call”

156
Q

What’s the result of the following code and why?

zero = 0
puts “Before each call”
zero.each { |element| puts element } rescue puts “Can’t do that!”
puts “After each call”

A

Before each call
Can’t do that!
After each call

It does so because it isn’t possible to call the each method on an Integer which is the value of the zero variable. If we remove the rescue block, the second puts method will not execute because the program will exit when it runs into the error. You can see why the word “rescue” is relevant here. We are effectively rescuing our program from coming to a grinding halt. If we give this same code the proper variable, our rescue block never gets executed.

157
Q

Can we save pre-existing errors?

A

Yes

divide.rb

def divide(number, divisor)

begin
answer = number / divisor

rescue ZeroDivisionError => e
puts e.message

end

end

puts divide(16, 4)
puts divide(4, 0)
puts divide(14, 7)

Here we are rescuing the ZeroDivisionError and saving it into a variable e. We then have access to the message method that the ZeroDivisionError object has available.

158
Q

What’s ZeroDivisionError?

A

Pre-existing Ruby error

159
Q

What do we say when something goes wrong?

A

An exception has been raised

160
Q

Ruby built in exceptions examples:

A
StandardError
TypeError
ArgumentError
NoMethodError
RuntimeError
SystemCallError
ZeroDivisionError
RegexpError
IOError
EOFError
ThreadError
ScriptError
SyntaxError
LoadError
NotImplementedError
SecurityError
161
Q

Stacks and methods

A

When ruby invokes a method, the method is added to Ruby’s ‘stack’.

The stack trace first tells us where the error occurred and why.

162
Q

What’s the stack trace for the error in this code?

1 def greet(person)
2  puts "Hello, " + person
3 end
4 
5 greet("John")
6 greet(1)
A

Error:
greeting.rb:2:in +': no implicit conversion of Fixnum into String (TypeError) from greeting.rb:2:in greet’
from greeting.rb:6:in `’

Stack trace:

The stack trace first tells us where the error occurred and why: line 2 of greeting.rb, and the error was because the types don’t match. The error occured due to the call made in the ‘main’ context on line 6, which contains the line that called the method with incorrect arguments, line 2.

163
Q

What’s the stack trace of this?

def space_out_letters(person)
  return person.split("").join(" ")
end
def greet(person)
  return "H e l l o, " + space_out_letters(person)
end

def decorate_greeting(person)
puts “” + greet(person) + “”
end

decorate_greeting(“John”)
decorate_greeting(1)

A

main -> decorate_greeting -> greet -> space_out_letters (passes result back) -> greet -> decorate_greeting -> main

Error:

H e l l o, J o h n
greeting.rb:2:in space_out_letters': undefined method split’ for 1:Fixnum (NoMethodError)
from greeting.rb:6:in greet' from greeting.rb:10:in decorate_greeting’
from greeting.rb:14:in `’

164
Q

Initialize a git repository command

A

git init

165
Q

How do you add a remote repository as a remote of existing local repo

A

git add remote origin “link goes here”

166
Q

List all remote repositories

A

git remote

167
Q

Rename a remote repository

A

git remote rename old_name new_name

168
Q

What does origin mean when used to work with remote repositories?

A

It’s an alias for the remote repo to use locally and interact with the remote repo

169
Q

What’s in git/config?

A

The .git/config file is where all the configuration settings for your local repository are held, and overrides any global settings.

170
Q

Set the upstream branch - what’s the message you receive that confirms this?

A

git push -u origin master

That -u flag sets the upstream repo, which causes our local master branch to track the master branch on the remote repo which is aliased as origin.

You will also see a message saying that you have set up your local master branch to track the remote master branch, thanks to the -u flag.

171
Q

What’s the benefit of an upstream branch?

A

Can use git push afterward to push the the remote repo

172
Q

Scenarios for using pull request?

A

Sometimes the code in your remote repository will contain commits you do not have in your local repository. In those situations, you will need to pull the commits from the remote repository into your local repository. There are four basic scenarios when you will run into this:

  1. You work on a team, and multiple people pushed code to the remote repository.
  2. You pushed to the remote repository from a different machine.
  3. Your project is public on GitHub and somebody contributed to it.
  4. You made a change to a file directly on GitHub.com.
173
Q

What does fetch do?

A

Will download the commit data for each branch that the remote repo contains.

Because we are currently working with our local master branch, the git fetch command will fetch the commits from the remote repo containing the tracked remote branch.

git fetch

174
Q

What does git diff do?

A

git diff master origin/master

This command tells git to compare the local master branch to the master branch on the remote repo which is aliased origin. Put another way, we’re comparing the commits in our local repository with the commits in the remote repository.

You can compare other branches

175
Q

What does pull do?

A

Pulls changes into local repo

git pull

Since the local master branch has been configured to track the origin/master branch, you do not have to specify what branch to pull from.

Could have used git pull origin master

The local repo is identical to the remote repo now

176
Q

What does clone do?

A

Pull down contents of existing remote repo into a new local repo, and add a remote to the local repo pointing to remote repo.

git clone

177
Q

When to use clone?

A

git clone is used mainly when you need to work with a remote repository, and do not yet have a local repository created. For example, if you just joined a new project, the first thing you’d likely do is git clone the project in order to start working on it locally.

Another common use case is if you want to pull down an open source project. For example, if you wanted to check out the source code for the popular open source web development framework, Ruby on Rails, you can issue this command:

git clone https://github.com/rails/rails.git

178
Q

What happens if you don’t specify the second parameter in the clone command?

A

If you don’t specify a directory name then the default behavior is that a new directory will be created with the same name as the cloned repo.

179
Q

Nest git repositories

A

Not allowed.

You are allowed to create another folder in a git repository, but not another git repository

180
Q

Why are parameters useful in a method

A

When you have data outside the method, but you want to use it inside the method

181
Q

What’s a method invocation?

A

Another name for calling a method

182
Q

What do we pass to a method when we call it?

A

arguments

183
Q

What are arguments

A

pieces of information which are passed to a method invocation to be modified or used to return a specific result

184
Q

Case statements and variables

A

You can save the result of a case statement to a variable

a = 5

answer = case a
  when 5
    "a is 5"
  when 6
    "a is 6"
  else
    "a is neither 5, nor 6"
  end

puts answer

185
Q

Case arguments

A

You dont need to give the case an argument, but you have to do a comparison in each when

a = 5

answer = case
  when a == 5
    "a is 5"
  when a == 6
    "a is 6"
  else
    "a is neither 5, nor 6"
  end

puts answer

186
Q

Ruby evaluating true/false expressions

A

In Ruby, every expression evaluates to true when used in flow control, except for false and nil

a = 5
if a
  puts "how can this be true?"
else
  puts "it is not true"
end
187
Q

Difference between do/while and loop

A

the code in loop gets executed at least once until the condition is hit