Array Inquiry

02 December 2014

Checking if an element exists in an array is a common operation. Ruby provides several elegant ways to do this.

Using include? Method

fruits = ["apple", "banana", "orange"]
fruits.include?("banana")
# => true
fruits.include?("grape")
# => false

Using any? Method

numbers = [1, 2, 3, 4, 5]
numbers.any? { |n| n > 3 }
# => true

Using member? Method

arr = ["a", "b", "c"]
arr.member?("b")
# => true

Performance Comparison

For simple presence checks, include? is the most efficient and readable option. It's optimized and O(n) complexity.

Best Practice

Use include? for simple checks and any? for conditional checks with blocks.

← Back to Blog

About the Author

Kameshwaran Sachithanantham

Software Engineer cum Project Manager with 11+ years of experience in React, Node.js, React Native, and Ruby on Rails.