From: Vladimir Date: 2012-04-13T18:52:25+09:00 Subject: Re: How to test if array element exists? On 04/13/2012 10:31 AM, Soul Surf wrote: > I'm new to Ruby and just want to test if an array element exists. Here's > a basic code snippet: > > array = [0,1,2,3] > > if [array[4]].empty? > puts 'empty' > end > if [array[4]].nil? > puts 'nil' > end > > element 4 does not exist in the array, but neither of the if statements > result in true? what would be an if statement to check that array[4] > does not exist? Thanks > Answer depends on what you want from check here is array arr = [1,2,nil,nil] puts arr[2] >> nil puts arr[3] >> nil You can have nil values as element, so maybe better check arr.length < your_element_number