0
0
Rubyprogramming~10 mins

Array methods (length, include?, flatten) in Ruby - Interactive Code Practice

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

Complete the code to get the number of elements in the array.

Ruby
numbers = [1, 2, 3, 4, 5]
count = numbers.[1]
puts count
Drag options to blanks, or click blank then click option'
Atotal
Bsize
Ccount
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method that does not exist like 'total'.
Confusing 'length' with 'include?'.
2fill in blank
medium

Complete the code to check if the array contains the number 3.

Ruby
numbers = [1, 2, 3, 4, 5]
has_three = numbers.[1](3)
puts has_three
Drag options to blanks, or click blank then click option'
Ahas?
Binclude?
Ccontains?
Dexists?
Attempts:
3 left
💡 Hint
Common Mistakes
Using methods that do not exist like 'contains?'.
Forgetting the question mark at the end of 'include?'.
3fill in blank
hard

Fix the error in the code to flatten the nested array into a single array.

Ruby
nested = [[1, 2], [3, 4], [5]]
flat = nested.[1]
puts flat.inspect
Drag options to blanks, or click blank then click option'
Aflatten
Bflatten!
Cflat!
Dflat
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'flatten!' which modifies the original array instead of returning a new one.
Using non-existent methods like 'flat' or 'flat!'.
4fill in blank
hard

Fill both blanks to create a hash with words as keys and their lengths as values, only for words longer than 3 letters.

Ruby
words = ["apple", "cat", "banana", "dog"]
lengths = words.each_with_object({}) do |word, h|
  if word.[1] [2] 3
    h[word] = word.[1]
  end
end
puts lengths
Drag options to blanks, or click blank then click option'
A.length
B>
Clength
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '.length' which causes a syntax error (double dot).
Using '<' instead of '>' for the condition.
5fill in blank
hard

Fill all three blanks to create a hash with uppercase words as keys and their lengths as values, only for words longer than 3 letters.

Ruby
words = ["apple", "cat", "banana", "dog"]
lengths = words.each_with_object({}) do |word, h|
  if word.[2] [3] 3
    h[word[1]] = word.[2]
  end
end
puts lengths
Drag options to blanks, or click blank then click option'
A.upcase
Blength
C>
Dcapitalize
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'capitalize' instead of 'upcase' for uppercase keys.
Using '<' instead of '>' in the condition.