w1d2 revisions Flashcards
When we want to select a certain number of items from an array, what method should we use?
Array#select
What does #dup do? When is it useful?
It is an inherited method from the Object class, and returns a copy of the object. It is useful when we do not want to modify the original object and/or ‘self’
What is the shorthand for reassigning values to multiple objects? How can we use it to swap the values of two variables?
var1, var2 = new_var1, new_var2
-‘var1’ now has the value of new_var1, var2 now has the value of new_var1
We can swap the values of variables like so:
var1, var2 = var2, var1
What would be the code to quickly get an array of lines from a file?
lines = File.readlines(‘filename’).map(&:chomp)
What is the following syntax short for?
arr.map(&:upcase)
arr.map do |elem|
elem.upcase
end
T/F: Enumerator#each returns the original object that has been modified by the code block.
T
As soon as we find ourselves adding a ‘!’ to a condition in an ‘if’ or ‘while’, what should we use instead?
‘unless’ or ‘until’, respectively. They are much cleaner.
What would be the code to quickly retrieve the first element of each element of a multidimensional array?
starts = arr.map(&:first)
USE MAP TO RETURN A NEW ARRAY AND EACH TO EITHER RETURN THE ORIGINAL OBJECT OR THE ORIGINAL OBJECT AFTER IT HAS BEEN MUTATED
What is a shorthand to sample a value from a range?
rand(start..end)
Explain the ‘’ operator
It returns -1 if the left-hand operand is less than the right hand operator, 1 if the opposite, and 0 if they are equal.
What does File::extname return?
The file extension
How can File::basename return ONLY the filename and not the extension?
File.basename(‘filepath’, “.*”)
When should we use Enumerator#any?
When we could use #each, but we only want to check if something occurs at least once:
def has_conflict?(new_course)
self.courses.any? do |enrolled_course|
new_course.conflicts_with?(enrolled_course)
end
end
How can we raise a generic error?
raise “error message” if condition
How can we raise a specific class of error?
raise ErrorClass.new(“error message”) if condition