Arrays: Ruby Docs Flashcards
What are the two arguments array.new accepts?
arr = Array.new(3, “something”)
==> [“something”, “something”, “something”]
How else can you create an array (with specific elements)?
Array.new([item, item, item])
How would you create an array using the index?
Array.new(3){ |index| index ** 2 } ------------------ # => [0, 1, 4] where index is just a variable name for the index
Accessing hash value within an array: Given
[“CAT”, {“HASHTHING”=>”hash value”}] how would you access the hash value
a[1][‘HASHTHING] ==> “hash value”
How do you return the an array if it is an array or nil if it is not?
Array.try_convert( thing to convert)
==> the array if it is one
==.> nil if not
Public Instance Method:
Given two arrays, how do you return an array of the intersection (common elements)?
The & method
[ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ]
Public Instance Method:
Given two arrays, how do you remove any elements of the second array from the first array?
Array Difference ( - ) [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #=> [ 3, 3, 5 ]
Public Instance Method:
How do you compare two arrays?
What will be returned?
Returns an integer (-1, 0, or +1) if this array is less than, equal to, or greater than the other
[ “a”, “a”, “c” ] <=> [ “a”, “b”, “c” ] #=> -1
[ 1, 2, 3, 4, 5, 6 ] <=> [ 1, 2 ] #=> +1
When are two arrays equal via == ?
When they contain the same number of elements and each one is equal to the corresponding element in the other array
what happens when your index range includes an element but the remainder is non existent?
returns the element that exists