Complete the code to group numbers by their parity (even or odd).
numbers = [1, 2, 3, 4, 5] groups = numbers.group_by { |n| n.[1] } puts groups
odd? groups by odd numbers, which is not what the question asks.to_s or abs does not categorize by parity.The even? method returns true for even numbers, so grouping by n.even? categorizes numbers into even and odd groups.
Complete the code to group words by their first letter.
words = ['apple', 'banana', 'apricot', 'blueberry'] groups = words.group_by { |word| word.[1] } puts groups
length groups by word length, not first letter.upcase returns the whole word in uppercase, not the first letter.The first method returns the first character of a string, so grouping by word.first groups words by their first letter.
Fix the error in the code to group numbers by their remainder when divided by 3.
numbers = [1, 2, 3, 4, 5, 6] groups = numbers.group_by { |n| n [1] 3 } puts groups
/ divides numbers but does not give remainder.* or - does not relate to remainder.The modulo operator % gives the remainder of division, so n % 3 groups numbers by their remainder when divided by 3.
Fill both blanks to group words by their length and select only words longer than 3 letters.
words = ['cat', 'dog', 'elephant', 'bee', 'ant'] groups = words.group_by { |word| word.[1] } filtered = groups.select { |length, words| length [2] 3 } puts filtered
size is also valid for length but only one correct answer is accepted here.< selects shorter words, not longer.Grouping by word.length groups words by their length. Selecting where length is greater than 3 filters only longer words.
Fill all three blanks to group numbers by their sign and select only positive numbers.
numbers = [-2, -1, 0, 1, 2] groups = numbers.group_by { |n| n.[1] } positive = groups.select { |sign, nums| sign == [2] } puts positive[[3]]
negative? groups negative numbers, not positive.false selects non-positive numbers.The positive? method returns true for positive numbers. Selecting groups where sign is true filters positive numbers. Accessing positive[true] gets the array of positive numbers.