w1d2 Flashcards
How do you require a file from the same directory as the file doing the require?
require_relative
What does require_relative do?
It loads a file from the same folder as the requiring file.
High-level: given an array, how would you find pairs of elements which have a sum of 0?
outer loop for the i to array.length element
inner loop for the i+i to array.length element
collect the pairs that sum to zero
What does Array#take do?
Returns first n elements from the array
Which method returns the first n elements from the array?
Array#take
What does Array#drop do?
Returns last n elements from the array
Which method returns the last n elements from the array
Array#drop
What’s the problem with doing this:
a = Array.new(3, [ ] )
a[0] «_space;“Hello”
What’s a better way? Why?
The empty array we pass to the Array constructor is actually a reference to an empty array. Each of the 3 elements in a will reference the same array. When we assign “Hello” to a[0], we actually assign it to all 3 elements.
Better way: a = Array.new(3) { [ ] }
This creates a new empty array reference for each element of a.
What’s the difference between the assignment operator in Ruby and C?
Describe what this does:
a = 4
a = 6
In Ruby, = does not mutate an object. Instead, it reassigns the variable so that it points to a new object.
a = 4 calls Fixnum.new(4), stores it somewhere, then returns a reference to this Fixnum and assigns it to a.
a = 6 calls Fixnum a second time, creating a second Fixnum, and changes a to point at the second Fixnum.
The original Fixnum(4) is still out there, until GC gets it.
What is syntactic sugar? Give an example
Shortcuts in the Ruby language that makes writing code easier.
x += 5
This does not call a special += method, instead, it is rewritten internally as:
x = x + 5
and then executed.
How do you conditionally assign something?
Use the ||= operator
What type of default value is safe to pass to a Hash or Array?
An immutable object. Fixnum or Float is safe.
What output do we get here (line-by-line):
cats = Hash.new( [ ] )
cats[“John”] «_space;“kiki”
cats
cats[“Bob”]
{ }
[“kiki”]
{ }
[“kiki”]
What’s the proper way to initialize a hash of arrays? Why do we use this syntax? What happens if we don’t?
a = Hash.new { |hash, key| hash[key] = [ ] }
We do this in order to create a new array reference for each new hash element.
If we don’t do the hash[key] = [ ] part, a reference to the new array will not be stored in the hash.
List 9 code smells
8-9: 5 stars 5-7: 4 stars 4-5: 3 stars 2-3: 2 stars 0-1: 1 star
Duplicated code Long methods Too many parameters Data clump Long method chains Indecent Exposure Speculative Generality God object Dead code