Array Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

any?

A

Returns true if any of the values in the block evaluates to true.

Example:

[1, 2, 3].any? { |num| num.odd? }
=> true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

assoc, #rassoc

A

.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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

reject

A

Same as .select but it selects values that evaluate to false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

take

A

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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

drop

A

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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

inject, #reduce (aliases)

Inherited from Enumerable module

A

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”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

index #rindex

A

.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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly