我刚开始使用红宝石,无法将头绕在积木上
它与匿名函数有何不同?
我想在什么情况下使用它?
我什么时候会选择它而不是匿名函数?
Ruby doesn't have anonymous functions like JavaScript (for example) has. Blocks have 3 basic uses:
Proc
sAn 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.