Skip to content

Instantly share code, notes, and snippets.

@swistak35
Created September 2, 2013 17:33
Show Gist options
  • Save swistak35/6415336 to your computer and use it in GitHub Desktop.
Save swistak35/6415336 to your computer and use it in GitHub Desktop.
Enumerable#find_and_replace(cond, &block)
1.9.3p362 :002 > [1,2,3,4,5].find_and_replace(:odd?, &:to_s)
=> ["1", 2, "3", 4, "5"]
1.9.3p362 :003 > [1,2,3,4,5].find_and_replace(Proc.new(&:odd?), &:to_s)
=> ["1", 2, "3", 4, "5"]
1.9.3p362 :005 > [1,2,3,4,5].find_and_replace(->(x) { x.odd? }, &:to_s)
=> ["1", 2, "3", 4, "5"]
1.9.3p362 :006 > [1,2,3,4,5].find_and_replace(->(x) { x.odd? }) do |x|
1.9.3p362 :007 > x.to_s
1.9.3p362 :008?> end
=> ["1", 2, "3", 4, "5"]
# Hashes!
1.9.3p362 :037 > h.find_and_replace(->(k,v) { v > 10 }) {|k,v| v.to_s }
=> [2, 3, "19"]
1.9.3p362 :038 > h.find_and_replace(->(k,v) { v > 10 || k == :key1 }) {|k,v| v.to_s }
=> ["2", 3, "19"]
1.9.3p362 :049 > h.find_and_replace(:odd?) {|k,v| v.to_s }
=> [2, "3", "19"]
module Enumerable
def find_and_replace(cond, &block)
self.map do |x|
if cond.instance_of?(Symbol)
res = Array(x).last.send(cond)
else
res = cond.call(*x)
end
res ? yield(*x) : Array(x).last
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment