0
0
Rubyprogramming~5 mins

Array methods (length, include?, flatten) in Ruby

Choose your learning style9 modes available
Introduction

Arrays hold many items together. These methods help you count items, check if an item is there, or make nested arrays simple.

When you want to know how many items are in a list.
When you want to check if a list has a certain item.
When you have a list inside a list and want to make it one simple list.
Syntax
Ruby
class Array
  # Returns the number of items in the array
  def length
    # built-in method
  end

  # Checks if the array includes a given item
  def include?(item)
    # built-in method
  end

  # Flattens nested arrays into one array
  def flatten
    # built-in method
  end
end

These are built-in methods in Ruby's Array class.

Use include? with a question mark because it returns true or false.

Examples
Counts how many items are in the array.
Ruby
numbers = [1, 2, 3, 4]
numbers.length # => 4
Checks if 'banana' is in the list (true) and if 'grape' is in the list (false).
Ruby
fruits = ['apple', 'banana', 'cherry']
fruits.include?('banana') # => true
fruits.include?('grape') # => false
Makes the nested arrays into one flat list.
Ruby
nested = [1, [2, 3], [4, [5]]]
nested.flatten # => [1, 2, 3, 4, 5]
Shows how these methods work on an empty array.
Ruby
empty = []
empty.length # => 0
empty.include?(1) # => false
empty.flatten # => []
Sample Program

This program shows how to use length, include?, and flatten on arrays. It prints the original array, its length, checks for items, and flattens a nested array.

Ruby
numbers = [10, 20, 30, 40]
puts "Original array: #{numbers}"
puts "Length: #{numbers.length}"
puts "Includes 20? #{numbers.include?(20)}"
puts "Includes 50? #{numbers.include?(50)}"

nested_array = [1, [2, 3], [4, [5, 6]]]
puts "\nNested array: #{nested_array}"
flat_array = nested_array.flatten
puts "Flattened array: #{flat_array}"
OutputSuccess
Important Notes

Time complexity: length is O(1), include? is O(n), flatten is O(n) where n is total elements.

Space complexity: flatten creates a new array, so O(n) extra space.

Common mistake: forgetting that include? checks for exact matches, so '20' (string) is different from 20 (number).

Use flatten when you want one simple list instead of nested lists. Use include? to check presence before searching or processing.

Summary

length tells how many items are in an array.

include? checks if an item is inside the array, returning true or false.

flatten turns nested arrays into one simple array.