Question

I've just started on ruby and can't wrap my head around blocks

How is it different from an anonymous function?

On what instance would I want to use it?

And when would I choose it over an anonymous function?

Was it helpful?

Solution

Ruby doesn't have anonymous functions like JavaScript (for example) has. Blocks have 3 basic uses:

  1. Creating Procs
  2. Creating lambdas
  3. With functions

An example of where blocks are similar to anonymous functions is here (Ruby and JavaScript).

Ruby:

[1,2,3,4,5].each do |e| #do starts the block
  puts e
end #end ends it

JS (jQuery):

$.each([1,2,3,4,5], function(e) { //Anonymous *function* starts here
  console.log(e);
}); //Ends here

The power of Ruby blocks (and anonymous functions) is the fact that they can be passed to any method (including those you define). So if I want my own each method, here's how it could be done:

class Array
  def my_each
    i = 0
    while(i<self.length)
      yield self[i]
      i+=1
    end
  end
end

For example, when you declare a method like this:

def foo(&block)
end

block is a Proc object representing the block passed. So Proc.new, could look like this:

def Proc.new(&block)
  block
end

Blocks, by necessity, are bound to a method. They can only be turned into an object by a method like I described above. Although I'm not sure of the exact implementation of lambda (it does extra arg checking), but it is the same idea.

So the fundamental idea of a block is this: A block of code, bound to a method, that can either be contained in a Proc object by an & argument, or called by the yield keyword.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top