A look through RAA and rubyforge doesn’t show any functional
programming libraries, are there any that I haven’t noticed? Any one
interested in starting functional.rb? Here are some functional
helpers I have used.
class Object
def tap
yield self
return self
end
end
require ‘enumerator’
module Enumerable
def map_msg(meth, *args)
if block_given?
map{|e| yield( e.send(meth, *args) )}
else
map{|e| e.send(meth, *args)}
end
end
def thread_map
map do |e|
Thread.new(e) {|thr_e| yield thr_e}
end.map_msg(:value)
end
def thread_map_msg( meth, *args )
if block_given?
map { |e| Thread.new(e) do |thr_e|
yield thr_e.send(meth, *args)
end }.map_msg(:value)
else
map { |e| Thread.new(e) do |thr_e|
thr_e.send( meth, *args )
end }.map_msg(:value)
end
end
end
puts “foobar”.tap{ gsub! /bar/, ‘’ } #=> foo
Well that prevents you from being able to access the enclosing scope,
but maybe that’s okay for a tap. You could always offer both by
checking block arity.
Well that prevents you from being able to access the enclosing scope,
but maybe that’s okay for a tap. You could always offer both by
checking block arity.
hrrrmmm. i wouldn’t say ‘prevents’ - but confuses
harp:~ > cat a.rb
class Object
def tap &b
b.arity == 1 ? yield(self) : instance_eval(&b)
return self
end
end