0
0
Rubyprogramming~10 mins

Why functional patterns complement OOP in Ruby - Test Your Understanding

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

Complete the code to define a method that returns the square of a number.

Ruby
def square(num)
  num [1] num
end
Drag options to blanks, or click blank then click option'
A+
B*
C-
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '*' will add the number to itself, not square it.
2fill in blank
medium

Complete the code to create an array of squares from 1 to 5 using map.

Ruby
squares = (1..5).[1] { |n| n * n }
Drag options to blanks, or click blank then click option'
Amap
Beach
Cselect
Dreduce
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'each' returns the original array, not the transformed one.
3fill in blank
hard

Fix the error in the code to filter even numbers from an array.

Ruby
evens = [1, 2, 3, 4, 5].[1] { |n| n.even? }
Drag options to blanks, or click blank then click option'
Amap
Beach
Creduce
Dselect
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'map' returns transformed elements but does not filter.
4fill in blank
hard

Fill both blanks to create a hash of word lengths for words longer than 3 characters.

Ruby
lengths = words.select { |word| word.length > 3 }.map { |word| [ [1], [2] ] }.to_h
Drag options to blanks, or click blank then click option'
Aword
Bword.length
Cword.size
Dword.upcase
Attempts:
3 left
💡 Hint
Common Mistakes
Using word.size is valid but not the expected answer here.
5fill in blank
hard

Fill all three blanks to create a hash of uppercase words and their lengths for words longer than 4 characters.

Ruby
result = words.select { |word| word.length [3] 4 }.map { |word| [ [1], [2] ] }.to_h
Drag options to blanks, or click blank then click option'
Aword.upcase
Bword.length
C>
Dword.downcase
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' will filter the wrong words.