Object#send and blocks/procs

Hi Guys,

I started to write this email as a question, but figured the answer in
the middle... :slight_smile:
So now I want to know if there's any problem with the code below, if
there is any performance hit or if there's a simpler way to turn Procs
back into blocks.

The question is how do I #send a method to an object with an attached
proc (not block)? The simplest way to reproduce is:

聽聽prc = lambda{ |a| a.upcase }
聽聽puts "aaa".send(:gsub, /./) # how do I pass prc as the block to
gsub?

Solution:

聽聽puts "aaa".send(:gsub, /./) { |x| prc[x] }

i.e. I have wrapped my Proc object within a block. Some interspersing of
'*' may be required for multiple params, as Markus pointed out in
another thread.

Cheers,
Assaph

Assaph wrote:

  prc = lambda{ |a| a.upcase }
  puts "aaa".send(:gsub, /./) # how do I pass prc as the block to gsub?

Try this:

  puts "aaa".send(:gsub, /./, &prc)

Cheers,
Gavin

You could also write (more generally):

  puts "aaa".send(:gsub, /./, &prc)

-- Markus

路路路

On Sun, 2004-09-26 at 22:47, Mehr, Assaph (Assaph) wrote:

Hi Guys,

I started to write this email as a question, but figured the answer in
the middle... :slight_smile:
So now I want to know if there's any problem with the code below, if
there is any performance hit or if there's a simpler way to turn Procs
back into blocks.

The question is how do I #send a method to an object with an attached
proc (not block)? The simplest way to reproduce is:

  prc = lambda{ |a| a.upcase }
  puts "aaa".send(:gsub, /./) # how do I pass prc as the block to
gsub?

Solution:

  puts "aaa".send(:gsub, /./) { |x| prc }

i.e. I have wrapped my Proc object within a block. Some interspersing of
'*' may be required for multiple params, as Markus pointed out in
another thread.

Cheers,
Assaph

"Mehr, Assaph (Assaph)" <assaph@avaya.com> writes:

Hi Guys,

I started to write this email as a question, but figured the answer in
the middle... :slight_smile:
So now I want to know if there's any problem with the code below, if
there is any performance hit or if there's a simpler way to turn Procs
back into blocks.

The question is how do I #send a method to an object with an attached
proc (not block)? The simplest way to reproduce is:

  prc = lambda{ |a| a.upcase }
  puts "aaa".send(:gsub, /./) # how do I pass prc as the block to
gsub?

Solution:

  puts "aaa".send(:gsub, /./) { |x| prc }

puts 'aaa'.send(:gsub, /./, &prc)

Gavin --

     *smile* I think that's twice in the last week or so. I'm just
going to have to learn to type faster!

          -- Markus

路路路

On Sun, 2004-09-26 at 22:56, Gavin Sinclair wrote:

Assaph wrote:

> prc = lambda{ |a| a.upcase }
> puts "aaa".send(:gsub, /./) # how do I pass prc as the block to gsub?

Try this:

  puts "aaa".send(:gsub, /./, &prc)

Cheers,
Gavin