On 12/17/06, Daniel Finnie <danfinnie / optonline.net> wrote:
>
> This would allow things like:
> ary = [4, nil, 6, nil]
> ary.select{|x| x.nil?}[1].set(2)
> ary # => [4, nil, 6, 2]

This will work in 1.8:

class Array
  def map_if!(condition)
    map! {|i| condition.call(i) ? yield i : i}
  end
end

ary.map_if! (lambda {|i| i.nil?) {|x| replacement for x}

1.9 allows blocks to take other blocks as arguments, which will (I
think!) allow something like

class Array
  def map_if!(&blk)
    _map_if(blk)
  end

  def _map_if(blk)
    map! {|i|
      blk.call(i) ? yield i : i
    }
  end
end

ary.map_if {|x| x.nil?} {|x| do something with x}

Seems more generally useful than setting selected elements by index
(internal versus external iterator)

martin