items with some nil valuesclean_items that uses compact on itemsclean_items arrayitems with some nil valuesclean_items that uses compact on itemsclean_items arrayitems with these exact elements: "apple", nil, "banana", nil, "cherry"Use square brackets [] to create the array and include nil where needed.
clean_items and set it to items.compact to remove all nil valuesUse the compact method on the items array and assign it to clean_items.
puts statement to print the clean_items arrayUse puts clean_items to display the array elements, each on its own line.
puts statement to print the clean_items array as a single line using inspectUse puts clean_items.inspect to print the array on one line with brackets.
What does the Ruby method compact do when called on an array?
compactcompact method creates a new array by removing all nil values from the original array.compact removes nil values without modifying the original array.Which of the following is the correct syntax to remove nil values from an array arr without changing arr itself?
arr = [1, nil, 2, nil, 3]
compact returns a new array without nil values and does not modify the original array.compact!compact! modifies the original array, so it changes arr. delete(nil) removes nil but modifies arr. remove_nil is not a Ruby method.What is the output of the following Ruby code?
arr = [nil, 5, nil, 10] new_arr = arr.compact puts new_arr.inspect puts arr.inspect
compact returnscompact returns a new array without nil values, so new_arr is [5, 10].arr remains unchanged as [nil, 5, nil, 10].Consider this Ruby code snippet:
arr = [1, nil, 2, nil, 3] arr.compact puts arr.inspect
Why does the output still include nil values?
compact behaviorcompact returns a new array without nil values but does not change the original array.arr still has nilarr.compact was called without assignment, arr remains unchanged and still contains nil.You have an array data = [nil, 0, false, '', nil, 5]. You want to remove only nil values but keep 0, false, and empty strings. Which code correctly does this?
compact doescompact removes only nil values and keeps all other values including 0, false, and empty strings.select { |v| v } removes all falsy values (nil, false, 0 is truthy in Ruby but empty string is truthy), so it removes false. reject!(&:nil?) modifies the original array. delete_if { |v| v.nil? } modifies original array.compact is simplest and returns new array without modifying original.Pass the test and this pattern moves unknown