简体   繁体   English

红宝石中关键字“do”的含义是什么?

[英]What is the meaning of the keyword “do”, in ruby?

I've seen a couple of do in Ruby, and I couldn't find a really good explanation of its purpose. 我见过一对夫妇do在Ruby中,我找不到它的目的一个很好的解释。 For example, a place where I saw a do was in the gemfile : 例如,我看到一个do的地方是在gemfile

group :development, :test do
    gem 'rspec-rails'
    gem 'rspec-its'
    gem 'simplecov', :require => false
    gem 'guard-rspec'
    gem 'spork-rails'
    gem 'guard-spork'
    gem 'childprosess'
    gem 'rails-erd'
    gem 'pry-rails'
    gem 'guard-rails'
    gem 'guard-livereload'
    gem 'guard-bundler'
end

I know what this code does, but I don't know the purpose of do . 我知道这个代码做什么,但我不知道的目的do I have my guesses, but I want them confirmed or denied by someone who knows more than me. 我有我的猜测,但我希望他们被比我更了解的人证实或否认。

do ... end (or alternatively { ... } ) creates a so-called block, which is a type of anonymous function in Ruby. do ... end (或者{ ... } )创建一个所谓的块,这是Ruby中的一种匿名函数。 In your example that block is passed as an argument to group . 在您的示例中,块作为参数传递给group group then does some bookkeeping to set the given groups as active, executes the block, and then deactivates the groups again. 然后, group执行一些簿记以将给定组设置为活动,执行块,然后再次停用组。

The do keyword is used together with the end keyword to delimit a code block. do关键字与end关键字一起用于分隔代码块。

More info on the difference of do end with brackets may be found here: http://ruby-doc.org/docs/keywords/1.9/files/keywords_rb.html#M000015 关于do end与括号的区别的更多信息可以在这里找到: http//ruby-doc.org/docs/keywords/1.9/files/keywords_rb.html#M000015

It is a block In other programming languages you using brackets, like this: {} . 它是一个block在其他编程语言中,您使用括号,如下所示: {} In ruby you can use: ruby你可以使用:

do

  #something code

end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM