From: Christopher Dicely Date: 2008-08-25T11:14:16+09:00 Subject: Re: indices of non nil elements in an array On Sun, Aug 24, 2008 at 6:20 PM, Patrick Doyle wrote: > a = [] > a[10] = "foo" > > a.nitems returns a count of the non-nil, items. What is the simplest > way to return the indices of "a" that are not nil? > > I'm sure there is some simple elegant way to do this, but I can't figure it out. If you need this frequently, you can monkeypatch Array to offer this functionality; like Array#detect but gathers the indexes instead of the values, and gathers indexes of non-nil values where no block is given: class Array def detect_indices result = [] each_with_index { |val, idx| (block_given? ? yield(val) : (not val.nil?)) && result << idx } result end end