`
sarstime
  • 浏览: 19701 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

programming ruby - 3

 
阅读更多

1, about method

Methods that act as queries are often named with a trailing ?, such as instance_of?.

 

Methods that are “dangerous,” or modify the receiver, may be named with a trailing !.

 

And methods that can be assigned to (a feature we discussed on page 29) end with an equals sign (=). ?, !, and = are the only “weird” characters allowed as method name suffixes.

 

Ruby lets you specify default values for amethod’s arguments—values that will be used if the caller doesn’t pass them explicitly. You do this using the assignment operator.

 

what if you want to pass in a variable number of arguments or want to capture multiple arguments into a single parameter? Placing an asterisk before the name of the parameter after the “normal” parameters does just that.

 

However, if the last parameter in a method definition is prefixed with an ampersand, any associated block is converted to a Proc object, and that object is assigned to the parameter.

 

When you call a method, you can explode an array, so that each of its members is taken as a separate parameter. Do this by prefixing the array argument (which must follow all the regular arguments) with an asterisk.

 

If the last argument to a method is preceded by an ampersand, Ruby assumes that it is a Proc object. It removes it from the parameter list, converts the Proc object into a block, and associates it with the method.

 

The first difference is that, unlike Procs, lambdas check the number of arguments passed.

 

The second difference is that lambdas have diminutive returns. What this means is that while a Proc return will stop a method and return the value provided, lambdas will return their value to the method and let the method continue on.

 

So, when to use Proc over lambdas and vice versa? Honestly, besides argument checking, the difference is just in how you see closures. If you want to stay in the mindset of passing blocks of code, keep with Proc. If sending a method to another method that can return a method makes sense to you, use lambdas. But, if lambdas are just methods in object form, can we store existing methods and pass them just like Procs? For that, Ruby has the something pretty tricky up its sleeve.

 

Just as you guessed, square is not a Proc, but a Method. The neat thing is that this Method object will act just like a lambda, because the concept is the same. This method however, is a named method (called square ) while lambdas are anonymous methods.

 

So to recap, we went through Ruby’s four closure types, blocks, Procs, lambdas and Methods. We also know that blocks and Procs act like drop-in code snippets, while lambdas and Methods act just like methods.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics