Solution for Drill: Researching Array Methods
Array#countInput: an array object
Output: an integer
By itself, Array#count is pretty straightfoward; it takes an array as input and returns the number of elements in the array as an integer.
array = ['a', 'b', 'b', 'd', 'b']
array.count #=> 5
Array's #count may take an argument or a block.
When an object is passed as an argument, the method returns the integer number of elements for which comparison by ==, as inherited or otherwise defined by the object's class, returns true.
array.count('b') #=> 3
When passed a block, Array#count returns the integer number of elements for which evaluating the block on the input array returns true.
array.count {|x| x >= 'b'} #=> 4
Solution for Challenge: Drill: Researching Array Methods. Started 2014-02-12T03:13:11+00:00
Array#transposeArray#transpose transposes an array matrix--that is, it flips the rows to columns and columns to rows.
Our boggle board challenge presents a good example for showcasing this method.
dice_grid = [['b', 'r', 'a', 'e'],
['i', 'o', 'd', 't'],
['e', 'c', 'l', 'r'],
['t', 'a', 'k', 'e']]
dice_grid.transpose #=>
# [["b", "i", "e", "t"],
# ["r", "o", "c", "a"],
# ["a", "d", "l", "k"],
# ["e", "t", "r", "e"]]
Most solutions that I saw (including my own)...
def get_col(col)
dice_grid.map {|row| row[col]}
end
get_col(0).join('') #=> biet
Another way....
def get_col(col)
dice_grid.transpose[col]
end
get_col(0).join('') #=> biet
There are a couple important assumptions/requirements for using this method successfully.
TypeError is raised.arr1 = ["a", "b", "c"].transpose #=> TypeError: no implicit conversion of String into Array
arr2 = [1,2,[3,4]].transpose #=> TypeError: no implicit conversion of Fixnum into Array
IndexError. The inner arrays themselves may hold different combinations of data types (e.g., arrays, hashes, numbers, strings, etc.), but each inner array must contain the same number of elements.# an array which holds 3 array elements, each of which is a 2-element array;
# one of which contains a 2-element array as one of its elements
arr3 = [[ 1, 2],
["a", "b"],
[ 3, [4,5]]]
# success!
arr3.transpose #=>
# [[1, "a", 3],
# [2, "b", [4, 5]]]
# an array which holds 3 array elements;
# of which two are 2-element arrays and one is a 3-element array
arr4 = [[1, 2], ["a", "b"], [3, 4, 5]]
# fail!
arr4.transpose #=> IndexError: element size differs (3 should be 2)