Solution for Challenge: Drill: Researching Array Methods. Started 2014-02-12T03:13:11+00:00
Array#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('') #=> bietAnother way....
def get_col(col)
dice_grid.transpose[col]
end
get_col(0).join('') #=> bietThere are a couple important assumptions/requirements for using this method successfully.
- The input array must a 2D array (an array of arrays). Every element of the array must be an array or else a
TypeErroris 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- The inner arrays must be of the same length or it will raise an
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)