From: Fritz Trapper on 30 Dec 2009 07:08 Correction: > def executer(obj, method) > f.method(1) > end Should be: def executer(obj, method) obj.method(1) end -- Posted via http://www.ruby-forum.com/.
From: Marnen Laibow-Koser on 30 Dec 2009 07:11 Fritz Trapper wrote: > Thanks for your quick replies. > > I see, my scenario is somewhat more complicated, than I wrote in my > initial posting. The point is, that I want to pass an object and a > method. > > Something like this: > > def executer(obj, method) > f.method(1) > end > > class x > def test(x) > p x > end > end > > o = x.new > executer(o, test) Why not just use o.send(:test) ? Best, -- Marnen Laibow-Koser http://www.marnen.org marnen(a)marnen.org -- Posted via http://www.ruby-forum.com/.
From: Fritz Trapper on 30 Dec 2009 07:13 Marnen Laibow-Koser wrote: > Why not just use o.send(:test) ? Thanks, that helps. -- Posted via http://www.ruby-forum.com/.
From: Jesús Gabriel y Galán on 30 Dec 2009 07:17 On Wed, Dec 30, 2009 at 1:00 PM, Jeff Peng <jeffpeng(a)netzero.net> wrote: > Jesús Gabriel y Galán: >> >> On Wed, Dec 30, 2009 at 12:42 PM, Fritz Trapper <ajfrenzel(a)web.de> wrote: >>> >>> I want to pass a reference to function as parameter to another function >>> and execute the passed function. Somthing like this: >>> >>> def executer(func) >>> func(1) >>> end >>> >>> def test(x) >>> p x >>> end >>> >>> executer(test) >>> >>> How to write this correctly in ruby? >> >> A typical way would be using blocks or procs: >> >> def executer >> yield 1 >> end >> >> executer {|x| puts "I got #{x}"} >> >> If you want something to handle around in a variable: >> >> func = lambda {|x| puts "I got #{x}"} >> executer(&func) # => I got 1 >> > > for &func, what's the "&" before "func" here? A method can receive regular parameters and a "special" block parameter. The & lets you pass a proc as that special block parameter, instead of a regular one: irb(main):033:0> executer(func) ArgumentError: wrong number of arguments (1 for 0) from (irb):33:in `executer' from (irb):33 from :0 Jesus.
From: Jesús Gabriel y Galán on 30 Dec 2009 07:18 On Wed, Dec 30, 2009 at 1:08 PM, Fritz Trapper <ajfrenzel(a)web.de> wrote: > Correction: >> def executer(obj, method) >> f.method(1) >> end > > Should be: > def executer(obj, method) > obj.method(1) obj.send(method, 1) > end executer(O.new, :the_method) Jesus.
First
|
Prev
|
Next
|
Last
Pages: 1 2 3 Prev: How to avoid \ escaping when using "= <<-EOF" ? Next: Why can't I use "or" here? |