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

programming ruby - 2

 
阅读更多

1, about closure

If the last parameter in a method definition is prefixed with an ampersand (such as &action),
Ruby looks for a code block whenever that method is called. That code block is converted
to an object of class Proc and assigned to the parameter. You can then treat
the parameter as any other variable. In our example, we assigned it to the instance
variable @action. When the callback method button_pressed is invoked, we use the
Proc#call method on that object to invoke the block.

So what exactly do we have when we create a Proc object? The interesting thing is that
it’s more than just a chunk of code. Associated with a block (and hence a Proc object)
is all the context in which the block was defined: the value of self and the methods,
variables, and constants in scope. Part of the magic of Ruby is that the block can still
use all this original scope information even if the environment in which it was defined
would otherwise have disappeared. In other languages, this facility is called a closure.


2, Regular expressions

match operators =~ (positive match) and !~ (negative match).

 

$& receives the part of the string that was matched by the pattern, $` receives the part of the string that preceded the match, and $' receives the string after the match.

 

The match also sets the thread-global variables $~ and $1 through $9. The variable
$~ is a MatchData object (described beginning on page 516) that holds everything you
may want to know about the match. $1, and so on, hold the values of parts of the match.

 

Within a pattern, all characters except ., |, (, ), [, ], {, }, +, \, ^, $, *, and ? match themselves. If you want to match one of these special characters literally, precede it with a backslash.

 

A backslash followed by an alphanumeric character is used to introduce a special match construct.

 

The patterns ^ and $ match the beginning and end of a line, respectively.

 

The sequence \A matches the beginning of a string, and \z and \Z match the end of a string. (Actually, \Z matches the end of a string unless the string ends with a \n, it which case it matches just before the \n.)

 

Similarly, the patterns \b and \B match word boundaries and nonword boundaries, respectively.

 

[characters] matches any single character between the brackets.

 

Within the brackets, the sequence c1-c2 represents all the characters between c1 and c2, inclusive.

 

Finally, a period ( . ) appearing outside brackets represents any character except a newline

 

... todo

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics