Ruby Intro - Arrays Flashcards
To teach some intro Ruby concepts and syntax
What do you use to select a range of items from an array set? Difference between the two syntaxes?
Ranges. “..” gives entire range while “…” leaves out the last item in the range.
How do you specify last (or second to last, etc.) value when getting a range of elements?
-1 gives last value. -2 gives second to last. Can be noted like so: “3..-1”
What’s the syntax for an iterator to access all elements in an array? (3 lines)
cool_things = [“race cars”, “lasers”, “aeroplanes”]
cool_things.each do |cool_thing|
puts “I like #{cool_thing}!”
end
# prints: I like race cars! # I like lasers! # I like aeroplanes!
What is «_space;called when used for inserting into arrays? The _____ ________.
The Shovel Operator
Concatenate two arrays into a new one without modifying the originals?
new_array = array1 + array2
Concatenate arrays AND modify original
use the concat method
three ways to find number of elements in an array. The last way only tells True/false whether array has elements.
“.length” “.count” “.empty?” (empty gives True or False)
For arrays, what is a Stack? What methods are used to treat an array like a Stack?
Has LIFO features.
Using push and pop and delete.
Pop will take out an item and also delete it from the array at the same time (does not need print. Printing is just for humans!)
POP acts like DELETE! It also does not print the popped item.
For arrays, what is a Queue. What methods are used to treat like a Queue?
Has FIFO features. Using push and “delete_at(0)”
nums = [] nums << 1 nums << 2 nums << 3 nums.delete_at(0) # => 1 nums # => [2, 3]
What is Array shift and unshift?
Shift is like “delete_at(0)” but also prints the item deleted. Unshift ADDS.
array = [1,2,3,4]
array.shift
# => 1
array # => [2,3,4]
array.unshift(5) # => [5,2,3,4]
in a single code line, create a sentence that expresses an array string (separated by commas) within the sentence. What is the method used to separate elements in the array?
“I like #{cool_things.join(“, “)}.”
What is the “, “ argument to join strings together called?
separator
What is method used to find out whether an array contains a specific object/element?
.include?( )
small_primes = [1, 2, 3, 5, 7, 11]
small_primes.include?(9)
# => false
How to find the position of first occurence of a specific object/element in an array?
.index( )
small_primes = [1, 2, 3, 5, 7, 11] small_primes.index(3) # => 2 small_primes.index(9) # => nil
Code to sort to a new array without changing the original array?
regular “sort”
arr = [3, 2, 1]
sorted_arr = arr.sort
sorted_arr # => [1, 2, 3]
arr # => [3, 2, 1]