Array Flashcards
What is partition
method?
Returns two arrays, the first containing the elements of enum for which the block evaluates to true, the second containing the rest.
(1..6).partition { |v| v.even? } #=> [[2, 4, 6], [1, 3, 5]]
How to check that array contain only one item?
[‘fa’].one? #=> true
[1, 3, 2].one? #=> false
Why do we need count
method? 3 options
Returns the number of elements.
If an argument is given, counts the number of elements which equal obj using ==.
If a block is given, counts the number of elements for which the block returns a true value
ary = [1, 2, 4, 2]
ary.count #=> 4
ary.count(2) #=> 2
ary.count { |x| x%2 == 0 } #=> 3
What is chunk
method?
Enumerates over the items, chunking them together based on the return value of the block. Return enumerator. Breaks and start chunking into another array when a condition inside the block changed.
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5].chunk { |n|
n.even?
}.each { |even, ary|
p [even, ary]
}
#=> [false, [3, 1]]
# [true, [4]]
# [false, [1, 5, 9]]
# [true, [2, 6]]
# [false, [5, 3, 5]]
How to use map with index?
array.map.with_index { |item, index| … }
[:a, :b, :c].map.with_index(2).to_a
#=> [[:a, 2], [:b, 3], [:c, 4]]
How to sort an array by the length in 2 directions?
arr.sort_by(&:length)
arr.sort_by(&:length).reverse
How to sort an array by several conditions?
You can pass the condition as an array to the block
arr.sort_by { |a| [-a.length, a] } # sort by length and by lexical order
How to implement the method ‘each’?
=> 2
class Array
def each
index = 0
length = self.size
while index < length yield(self[index]) index += 1 end end end
[1,2,3].each { |a| puts a + 1 }
# => 3
# => 4
How to implement the method ‘map’?
=> 2
class Array
def map
index = 0
new_array = []
while index < self.length new_array << yield(self[index]) index += 1 end new_array end end
[1,2,3].map { |a| a + 1 }
# => 3
# => 4
How to compare 2 objects of custom class?
include Comparable and define <=>
class Animal
include Comparable
attr_reader :age
def initialize(age)
@age = age
end
def <=>(value)
if self.age < value.age
-1
elsif self.age == value.age
0
elsif self.age > value.age
1
end
end
end
animal1 = Animal.new(10)
animal2 = Animal.new(20)
p animal1 <= animal2 #=> true
How to add array functionality to your custom class?
include Enumerable module and define method ‘each’
class WordSplitter
include Enumerable
attr_reader :word
def initialize(word)
@word = word
end
def each
word.chars.each do |char|
yield(char)
end
end
end
WordSplitter.new(‘hello’).map { |a| a + ‘a’ }
How to check that all values of the array are true for specif conditions?
array.all?(&:even?)
How to group array elements by 2 with offset by 1?
[1,2,3,4].each_cons(2).each { |a| p a }
# =?
[1, 2]
[2, 3]
[3, 4]
How to return first or last 3 elements of array?
arr.first(3)
arr.last(3)
What does ‘splat operator’ mean?
numbers = *[1, 2], 3