Complete the code to include the Enumerable module in the class.
class Collection include [1] end
The Enumerable module is included by writing include Enumerable inside the class.
Complete the code to define the required method for Enumerable to work.
class Collection include Enumerable def [1] @items.each { |item| yield item } end end
The Enumerable module requires the class to define an each method that yields items.
Fix the error in the code to use Enumerable's map method correctly.
collection = Collection.new collection.instance_variable_set(:@items, [1, 2, 3]) result = collection.[1] { |x| x * 2 }
each which returns the original collection, not a transformed one.for_each.The map method is provided by Enumerable and returns a new array with the results of running the block on each element.
Complete the code to create a hash with word lengths for words longer than 3 characters.
words = ['cat', 'house', 'dog', 'elephant'] lengths = words.inject({}) { |hash, word| word.length [1] 3 ? hash.merge(word: word.length) : hash }
In Ruby, using Enumerable's inject to build a hash conditionally, merge word: word.length when word.length > 3.
Fill all three blanks to filter and transform a collection using Enumerable methods.
numbers = [1, 2, 3, 4, 5] result = numbers.[1] { |n| n [2] 2 == 0 }.[3] { |n| n * 10 }
filter which is not a Ruby Enumerable method.each instead of map for transformation.select filters elements where the block returns true. The modulo operator % checks for even numbers. Then map transforms each number by multiplying by 10.