Thursday, May 31, 2012

Making a clear concept on passing &block

If we want to pass simple arguments we can use simply

def my_function(*args)
end

But if we want to pass a block of code to the function, at that time we need &block. We can pass &block simply as:

def my_function(args, &block)
  #here args are arguments
  #&block is the block of code we have passed through
end

i.e my_function(["a","b","c"], block_of_code )
An example illustrating the best scenerio:

def variable(&block)
  puts ‘Here goes:’

  case block.arity
  when 0
    yield
  when 1
    yield ‘one’
  when 2
    yield ‘one’, ‘two’
  when 3
    yield ‘one’, ‘two’, ‘three’
end

puts ‘Done!’

end

We’re declaring block as a method parameter here so we’ll have more access to it. The ampersand in front indicates that it’s going to be take the code block and put it into the Proc object block. Once we’ve got block we can see how many parameters it takes (Proc#arity) and deal with it accordingly. So how does that work?

variable {} »

Here goes:
Done!


variable { |x| puts x } »

Here goes:
one
Done!


variable { |x,y| puts x, y } »


Here goes:
one
two
Done!


variable { |x,y,z| puts x, y, z } »

Here goes:
one
two
three
Done!

No comments:

Post a Comment