From: lianliming Date: 2007-12-11T18:35:00+09:00 Subject: Re: Find the first non-nil element in an array Really helpful, thx! > > Hi all, > > > Is there any build-in method of class Array which can be used to find > > the first non-nil element in an array? I can't find any so I am trying > > to achieve it by my own approach. I don't think my approach is smart > > enough, so I would like to know better one to do so. Here is what I am > > doing: > > > a = [nil, "hello", "world"] > > b = a > > b.compact! > > first_non_nil_elem = b.first > > > I don't call "compact!" directly on a because it will change a's > > structure, I want to reserve nil elements in a. > > > Any suggestions are really appreciated! > > You can use Enumerable#find, which will return the first item in the array for > which the block returns true: > > a = [nil, "hello", "world"] > puts a.find{|i| !i.nil?} > => "hello" > > By the way, you can use compact, instead of compact! to avoid using the > temporary variable b: > > a = [nil, "hello", "world"] > first_non_nil_elem = a.compact.first > > While compact! removes the nil elements from the receiver, compact returns a > new array with the nil element removed. > > I hope this helps > > Stefano