开发者

Please explain this code from watchr

I'm learning to use watchr, a开发者_如何转开发 ruby gem that watches files and runs something if they change

watch( 'test/test_.*\.rb' )  {|md| system("ruby #{md[0]}") }
watch( 'lib/(.*)\.rb' )      {|md| system("ruby test/test_#{md[1]}.rb") }

Specifically, I don't understand what md[0] and md[1] are. I know that 'test/tests_.*\.rb' is a regular expression and it's retrieving a list of files. I also know that |md| represents filenames that match the regular expression. But I'm not sure what md[0] and md[1] would point to


I suspect that md is a MatchData instance, where [0] it the entire matched text and [1] is the first captured sub-expression), in this case the filename inside the lib directory, without the extension.


Ruby's regular expression operator (=~) returns an object that responds to :[]. The values 0 and 1 refer to the matched string and the first group (the part in the parentheses).

So for example if the strings being tested were:

"test/test_sample.rb"
"lib/sample.rb"

Then the first expression (/test/test_.*.rb/) would match "test/test_sample.rb", and the second expression (/lib/(.*).rb/) would match "sample". You can see this in the console:

> /test\/test_.*\.rb/ =~ "test/test_sample.rb"
# => 0
> $~[0]
# => "test/test_sample.rb"
> /lib\/(.*)\.rb/ =~ "lib/sample.rb"
# => 0
> $~[0]
# => "lib/sample.rb"
> $~[1]
# => "sample"

md stands for MatchData, which is the class of the object Ruby uses to return the result of the regex match.


zetetic's answer is correct; md is an instance of Rudy's MatchData class, which is the result of applying the regular expression on the modified file (see String#match).

The relevant line from the Watchr source code is at: https://github.com/mynyml/watchr/blob/17fa9bf80998483f9cf69a934bbcb726a0c389fa/lib/watchr/script.rb#L204

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜