0
0
Rubyprogramming~10 mins

Why Enumerable is Ruby's most powerful module - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to include the Enumerable module in the class.

Ruby
class Collection
  include [1]
end
Drag options to blanks, or click blank then click option'
AEnumerableClass
BEnumerableModule
CEnumerable
DEnumerableMixin
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong module name like EnumerableModule or EnumerableClass.
Forgetting to include the module.
2fill in blank
medium

Complete the code to define the required method for Enumerable to work.

Ruby
class Collection
  include Enumerable

  def [1]
    @items.each { |item| yield item }
  end
end
Drag options to blanks, or click blank then click option'
Aeach
Bloop
Citerate
Deach_item
Attempts:
3 left
💡 Hint
Common Mistakes
Defining a method with a different name like each_item or iterate.
Not yielding items inside the method.
3fill in blank
hard

Fix the error in the code to use Enumerable's map method correctly.

Ruby
collection = Collection.new
collection.instance_variable_set(:@items, [1, 2, 3])
result = collection.[1] { |x| x * 2 }
Drag options to blanks, or click blank then click option'
Amap
Bcollect
Ceach
Dfor_each
Attempts:
3 left
💡 Hint
Common Mistakes
Using each which returns the original collection, not a transformed one.
Using a non-existent method like for_each.
4fill in blank
hard

Complete the code to create a hash with word lengths for words longer than 3 characters.

Ruby
words = ['cat', 'house', 'dog', 'elephant']
lengths = words.inject({}) { |hash, word| word.length [1] 3 ? hash.merge(word: word.length) : hash }
Drag options to blanks, or click blank then click option'
A:
B>
C<
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong separator like comma instead of colon.
Using wrong comparison operators like < or ==.
5fill in blank
hard

Fill all three blanks to filter and transform a collection using Enumerable methods.

Ruby
numbers = [1, 2, 3, 4, 5]
result = numbers.[1] { |n| n [2] 2 == 0 }.[3] { |n| n * 10 }
Drag options to blanks, or click blank then click option'
Aselect
B%
Cmap
Dfilter
Attempts:
3 left
💡 Hint
Common Mistakes
Using filter which is not a Ruby Enumerable method.
Using wrong operators instead of modulo.
Using each instead of map for transformation.