Start with the NestedArray
example here. Add the following methods:
count
that takes a block and returns the number of elements
that return a non-false value on this block. For instance:
na = NestedArray.new([[6,7],[8],[[9, 6]]])
na.count {|y| (y < 8)} # returns 3
We will write this one together.
find
that takes a block and returns the first element it encountered that satisfies the condition in the block; returns nil
otherwise. For instance, on the above array na.find {|y| (y >= 8)}
returns 8, and na.find {|y| (y >= 100)}
returns nil.
map
that takes a block and returns a new nested array that results from applying this block to every element, preserving the nested structure. For instance, na.map {|y| y - 1}
will return a new nested array [[5,6],[7],[[8, 5]]]
select
that takes a block and returns a new nested array that is the result of selecting only elements that satisfy the condition. The structure of the original nested array is preserved, except that empty subarrays are dropped:
na.select {|y| y > 6} # results in [[7],[8],[[9]]]
na.select {|y| y > 7} # results in [[8],[[9]]]
push
or <<
to add an element at teh end of an array); Ruby if/else variants (know when to use "end", etc.)