From: Robert Klemme Date: 2004-08-07T04:46:25+09:00 Subject: Re: Defining a new function by composition "Edgardo Hames" schrieb im Newsbeitrag news:478c16ae0408061209424c2032@mail.gmail.com... > Hi. > > I would like to add a method to the Array class, say Array#pop! which > is actually split!(-1). But then, I can think of a more general > problem: define a new function by composition of two or more > functions. > In Haskell, I can do something like > > f :: a -> b -> c > f x y = something > > g::b -> c > g = f some_value > > What is the Ruby equivalent of this? > > Regards, > Ed > > How about class Array def pop!() split!(-1) end end Note: pop! and split! are not functions but methods. So you always have an implicit argument (named 'self' in Ruby). I think this does not lend easily to chaining the way you seek. Of course, for the general case you could do something like this: module Kernel private def chain(name, *funcs) eval "def #{name}(*a) #{funcs.map {|f| "#{f}("}}*a#{")" * funcs.size} end" end end >> def foo(x) "<#{x}>" end => nil >> def bar(x) "[#{x}]" end => nil >> chain :xxx, :foo, :bar => nil >> xxx 100 => "<[100]>" Or a more functional approach: module Kernel private def chain2(*funcs) lambda {|*a| funcs.inject(a){|val, fun| send(fun, *val) } } end end >> xx2 = chain2 :bar, :foo => # >> xx2.call 100 => "<[100]>" Note the different order. Regards robert