Funny Symbol FAQ

Gavin,

Sorry, just see the & in the faq, but *name is not there?

for the &, I don’t know why we need &? It seems to be used for Iterators
with a block? I wrote the following code in my program:

def test(source)
namelist=[]
source.each do |s|
namelist << s
yield s
end
return namelist
end
nl=test(anArray) do |a|
print a,"\n"
end

Will this code work? i.e., the iterator will work, and an array will be
returned to nl? I am not very clear how to write a method that both return a
value and accept a block? Is it related to the use of & ?

Thanks!
Shannon

···

Add photos to your e-mail with MSN 8. Get 2 months FREE*.
http://join.msn.com/?page=features/featuredemail

def test(source)
  namelist=
  source.each do |s|
    namelist << s
    yield s
  end
  return namelist
end
nl=test(anArray) do |a|
     print a,"\n"
   end

Will this code work?

just try it :slight_smile:

                     i.e., the iterator will work, and an array will be
returned to nl? I am not very clear how to write a method that both return a

  yes, when #yield will be called ruby will test if a block was given to
  the method #test and call it with `s' as argument

value and accept a block? Is it related to the use of & ?

no,

When you write

   def test(source, &block)
      # ...
   end

ruby internally make something like this

   def test(source)
      block = Proc.new if block_given?
      # ...
   end

This can be usefull when you want to pass the block to another method, for
example

   def aa
      yield 12
   end

   def bb(&block)
      aa(&block)
   end

   bb {|i| p i}

the block is not automatically "propagated" when a method call another
method, this is why you must give it to #aa.

You can also use &block, just to store a Proc object and re-use it after,
for example

   class A
      attr_accessor :a

      def initialize(&block)
         @block = block
      end

      def compute
         @block[@a]
      end
   end

   a = A.new {|i| p i * 2 }
   a.a = 12
   a.compute
   a.a = 24
   a.compute

Guy Decoux

Gavin,

Sorry, just see the & in the faq, but *name is not there?

Thanks for the suggestions. I’ll clarify & and add *name in the near future.

Gavin

···

From: “Shannon Fang” xrfang@hotmail.com

[…]

You can also use &block, just to store a Proc object and re-use it after,

And to pass in a proc object when a method is expecting a block, e.g.
a.each(&block)

martin

···

ts decoux@moulon.inra.fr wrote: