w1d1 Flashcards
Explain the following code:
arry[1..6]
Returns the 2nd through 7th elements of the ‘arry’ array
What is the difference between [2..4] and [2…4]
Three periods is not inclusive of the last element; two periods is.
Explain the following code:
arry[2..-1]
Returns the third through the last element of the array.
T/F: Never modify an array while iterating through it.
T; You can get stuck in an infinite loop
What is an advantage of Array#concat?
It modifies the first array by including references to the second array; very little memory cost.
Explain Array#include? and Array#index
include? returns a Boolean for finding the argument, #index returns the index of the element as an integer or nil if it is not found.
Explain the array methods: #sort, #sort!, #shuffle, #sample
sort sorts an array, with the smallest element at index 0
T/F: It doesn’t matter if arrays are heterogeneous (contain more than one type)
F; They can, but should be homogenous whenever possible.
Y/N: Will the following code execute?
“this is my sentence”[5, 2]
Yes; when given arguments like [int, int], the first argument is the starting index of the substring and the second argument is the length of the substring. For this reason, the code returns “is”
Explain the following string methods: #strip, #chomp, #gsub
strip removes leading and trailing whitespace
When a hash is used with an enumerable, what gets passed to the block?
|key, value|
When merging hashes with #merge, what will happens when a key is shared but each hash has a different value for the key?
The hash which is being merged (the argument) into the other hash takes precedence.
What is a quick way to check if a hash has a key?
has_key?
What is the difference between Enumerable#each and Enumerable#map (also known as Enumerable#collect)? When should you use them?
each returns the original UNMODIFIED array, while #map returns a new array with the computed values.
Use #each when you only want the method’s side-effects; use #map when you want to use the returned (computed) values.
Explain Enumerable#inject
We pass inject an initial value and a block. The code block takes the current accumulator value and the next element in the Enumerable . The block is run, and the accumulator value is updated with the block’s result. When all elements have been processed, the accumulator value is returned.
nums = [1, 2, 3, 4, 5]
nums.inject(0) do |accum, element| # accum is initially set to 0, the method argument
accum + element
end
This code returns 15 (the sum of all the elements)