From: Joel VanderWerf Date: 2010-09-07T02:58:03+09:00 Subject: Re: Odd functional programming question On 09/06/2010 06:40 AM, Peter Hickman wrote: > Ok this is probably not really functional programming but I was just > noodling about with Ruby when I thought "it would be quite nice if I > could do X". In this case X is as follows: > > def X(text, action) > x.action > end > >>> X("abcedf", size) > => 6 >>> X("abcdef", upcase) > => "ABCDEF" >>> X("abcdef", gsub(/[aeiouy]/, '_')) > => "_bcd_f" > > Quite clearly this does not actually work, otherwise I wouldn't be > asking. But is there some way in Ruby to do something like this? > Looks like a case for #instance_exec. def foo(x, &action) x.instance_exec(&action) end p foo("abcedf") {size} p foo("abcdef") {upcase} p foo("abcdef") {gsub(/[aeiouy]/, '_')} # unlike #send, you can have more complex code than one single # method call p foo("abcdef") {self+reverse} # also #instance_exec lets you pass thru args, which gives you # some flexibility in how you factor actions def bar(x, *args, &action) x.instance_exec(*args, &action) end p bar("abcdef", /[aeiouy]/, '_') {|pat, str| gsub(pat, str)}