w2 misc Flashcards
How do you cast in Ruby?
CastType(val)
What does Array#compact do?
Removes all nils.
Where should you put a collection of functions with no corresponding data?
In a module.
In a []= method, is the following argument acceptable:
[2, 2]
No; you must call it with Class[[x y]]
What can we do if the super version of a function returns something?
We can store it in a variable.
How far do exceptions travel when raised?
They travel up the call stack until they are handled. If they are not, the program exits.
If a function will be used in a child class but not in the parent class, how should it be declared in the parent class?
It should be declared to raise an error if called in the parent class, then overwritten in the child class with the specific behavior.
How can we set up a parent class to access the constants of an inherited class?
Use the following syntax in the parent class, then declare the constant in the child class:
self.class::CONSTANT
How do we pass an array of two elements to a block, when we want to access each element separately?
rows_with_cols_arr.each do |dx, dy|
How can we use a ternary operator to toggle a value?
(color == :white) ? -1 : 1
How can we use the ternary operator to set the value of a variable?
color = (color == ‘white’) ? ‘black’ : ‘white’
T/F: You can include more than one module in a class.
T; only multiple inheritance is invalid.
What is one way to catch many types of custom errors?
Make one custom error class which all other custom errors inherit from, then rescue the parent custom class (this will catch all inherited exceptions)
Explain #each_with_object
each_with_object([]) do |(dx, dy), moves|
‘moves’ it the blank array, and the first block argument is the object that each was called on.
Make an 8x8 grid
a = Array.new(8) { Array.new(8) }