Array Flashcards
any?
Returns true if any of the values in the block evaluates to true.
Example:
[1, 2, 3].any? { |num| num.odd? }
=> true
assoc, #rassoc
.assoc(obj) earches through an array whose elements are also arrays.
If the first element of the array matches obj it will return the whole array.
Otherwise it returns nil.
.rassoc(obj) does the same for the second element.
arr = [[1, 2], [3, 4], [5, 6]]
arr.assoc(3)
=> [3, 4]
reject
Same as .select but it selects values that evaluate to false.
take
Takes the number (say 2 or whatever) given as an argument and returns the first 2 or whatever elements in the array.
arr = [1, 2, 3, 4, 5]
arr.take(3)
=> [1, 2, 3]
drop
Opposite it #take as in it drops the first given number of elements and returns the rest.
arr = [1, 2, 3, 4, 5]
arr.drop(2)
=> [3, 4, 5]
inject, #reduce (aliases)
Inherited from Enumerable module
Given an array, they compute all the elements: (5..10).inject(:*)
=> 151200
Can also supply an initial counter
(5..10).reduce(1)
=> 46
If initial counter is not supplied the first element in the collection is the initial counter.
%w[cat fox bear].inject do |memo, word|
memo.length > word.length ? memo : word
end
=> “bear”
index #rindex
.index returns first element of array that’s equal to the argument specified:
[“a”, “b”, “c”].index(“b”)
=> 1
.rindex returns the last element in array that matches the argument:
[“a”, “b”, “b”, “c”].rindex(“b”)
=> 2