arrays Flashcards
How do I take the last item off any array?
array.pop
How do I add an item onto an array?
array.push or array «_space;“another string”
How do I remove an item from an array?
- a.delete_at(1) … at index 1
- delete(1) …. delete the number 1
Which method iterates through an array and deletes any duplicates? Is it destructive?
array. uniq
array. uniq!
b = [2, 3, 4]
b.pop
What is the return of b.pop?
4
How do I add a value to the front of a list?
array.unshift(1)
How do I convert a nested array and create a one dimensional array?
array.flatten
What method do I use to see if the argument given is in the array?
array.include?(4)
it returns a boolean, true or false
What does each_index do?
The each_index method iterates through the array much like the each method, however, the variable represents the index number as opposed to the value at each index. It passes the index of the element into the block and you may do as you please with it. The original array is returned.
irb: 001 > a = [1, 2, 3, 4, 5] => [1, 2, 3, 4, 5] irb: 002 > a.each_index { |i| puts "This is index #{i}" } This is index 0 This is index 1 This is index 2 This is index 3 This is index 4 => [1, 2, 3, 4, 5]
What does each_with_index do?
each_with_index gives us the ability to manipulate both the value and the index by passing in two parameters to the block of code. The first is the value and the second is the index. You can then use them in the block.
irb: 001 > a = [1, 2, 3, 4, 5] => [1, 2, 3, 4, 5] irb: 002 > a.each_with_index { |val, idx| puts "#{idx+1}. #{val}" } 1. 1 2. 2 3. 3 4. 4 5. 5 => [1, 2, 3, 4, 5]
How do I order an array? Is it destructive?
array.sort
it is a non-destructive method.
What does the product method do?
The product method can be used to combine two arrays in an interesting way. It returns an array that is a combination of all elements from all arrays.
irb :001 > [1, 2, 3].product([4, 5])
=> [[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
When no argument is given, what method returns the last element?
a.last
example:
a = [:foo, ‘bar’, 2]
a.last(2) # => [“bar”, 2]
When no argument is given, what method returns the first element?
a.first
example:
a = [:foo, ‘bar’, 2]
a.first(2) # => [:foo, “bar”]
What does .join do?
Array#join returns a string with the elements of the array joined together.
example:
str = ‘How do you get to Carnegie Hall?’
arr.join # => “HowdoyougettoCarnegieHall?”