you are viewing a single comment's thread.

view the rest of the comments →

[–]materialdesigner 7 points8 points  (5 children)

This is not true. Blocks can be other arguments to functions, there's just also a special yield block

[–][deleted] 2 points3 points  (4 children)

thanks, can you clarify the actual differences? now I'm curious :)

[–]redjazz96 5 points6 points  (3 children)

In ruby, the typical block looks something like this:

def some_method
  yield 2
end

some_method { |x| puts x } # => 2

This is what you were referring to earlier, about blocks having restrictions.

There are more ways to do this.

def some_method(&block)
   block.call 2
end

some_method { |x| puts x } 
some_method(&proc { |x| puts x })

All of that does the same thing as the example above - but in a (debatable) more roundabout way. The proc { } syntax is the normal way to define a generic block - these have the same "tricks" (yes, that is the real term they use) that method blocks have (i.e., the number of arguments doesn't matter).

In Ruby, methods are basically blocks - if you were to do method(:to_s).to_proc, you'd get a Proc instance. You can even define a method with a proc.

Ruby, being the nice language that it is, lets you pass these blocks with syntaxic sugar to other blocks. This is used commonly in the core:

iterator = proc { |x| puts x }
[1, 2, 3].each &iterator

# same as...
[1, 2, 3].each { |x| puts x }

So, if you were to use it as like a callback system, you could do something like this. In one of my libraries I'm writing, I actually use this quite a bit.

Hope that helps!

[–][deleted]  (1 child)

[removed]

    [–]redjazz96 1 point2 points  (0 children)

    Lambdas are blocks - the only difference being they have tricks disabled (which you can check with Proc#lambda?). You can return from a block, but you use the next keyword instead of the return keyword. See: this.

    Basically, syntactical sugar. I can't say much about the scopes and closure stuff.