Returning Procs from methods?

I’ve got something which basically does this:

some_string.scan(/(whatever)/).each &do_stuff

where &do_stuff is a Proc.

currently there’s a case/when that assigns different Procs to do_stuff
depending on the value of some_string.

what I want to do is something like this:

some_string.scan(/(whatever)/).each do_stuff

where do_stuff() is a method which figures out what Proc to return to
the each().

however, I can’t seem to build a method which returns a Proc.

can it be done?

On 11/29/06, Giles B. [email protected] wrote:

some_string.scan(/(whatever)/).each do_stuff

where do_stuff() is a method which figures out what Proc to return to
the each().

however, I can’t seem to build a method which returns a Proc.

can it be done?

sure

def do_stuff
lambda {|a| a+1}
end

b = [1,2].map(&do_stuff)

/Robert F.

awesome! thank you.

On 11/29/06, Robert F. [email protected] wrote:

sure

def do_stuff
lambda {|a| a+1}
end

b = [1,2].map(&do_stuff)

lambda {|a| a+1} is the new “hello world” :slight_smile:

martin

Giles B. wrote:

some_string.scan(/(whatever)/).each do_stuff

where do_stuff() is a method which figures out what Proc to return to
the each().

however, I can’t seem to build a method which returns a Proc.

can it be done?

The foo method returns the proc

def foo
lambda { |x| x + 2 }
end

foo.call(4) #6

def other_foo(&b)
b
end

var = other_foo { |x| x + 2 }
var.call(4) #6

On 11/29/06, Giles B. [email protected] wrote:

however, I can’t seem to build a method which returns a Proc.

can it be done?

Yes, but you still need to prefix it with a & when passing it to a
method that expects a block.

irb(main):001:0> def foo
irb(main):002:1> lambda {|x| x+1}
irb(main):003:1> end
=> nil
irb(main):004:0> (1…10).map foo
ArgumentError: wrong number of arguments (1 for 0)
from (irb):4:in `map’
from (irb):4
irb(main):005:0> (1…10).map &foo
=> [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

martin