group_by to categorize words by their length?words = ['cat', 'dog', 'bird', 'fish'] groups = words.group_by { |word| word.length } puts groups
group_by returns a hash where keys are the result of the block and values are arrays of elements.The group_by method groups elements by the value returned from the block. Here, words are grouped by their length, so keys are lengths and values are arrays of words with that length.
group_by method return when called on an array?group_by.group_by returns a hash where each key is the result of the block for grouping, and each value is an array of elements that belong to that group.
numbers = [1, 2, 3, 4] groups = numbers.group_by do |n| if n % 2 == 0 'even' else 'odd' end end puts groups
end.The block passed to group_by has an if statement but is missing the closing end for the block itself, causing a syntax error.
pairs = [[1, 'a'], [2, 'b'], [1, 'c'], [2, 'd']] groups = pairs.group_by { |pair| pair[0] } puts groups
group_by keeps the original elements grouped by the key returned from the block.The code groups the pairs by the first element of each pair. The result is a hash with keys 1 and 2, and values are arrays of pairs starting with those keys.
group_by to count how many words start with each letter?Option B groups words by their first letter, then maps each group to a pair of letter and count, finally converts the array of pairs back to a hash.
Option B uses transform_values(&:count) but transform_values requires Ruby 2.4 or later.
Option B uses &:first which works for strings, but returns an array of [letter, count] pairs instead of a hash.
Option B calls count on the grouped hash, which returns the number of keys, not counts per group.