Miika Vuorio
Miika Vuorio

Reputation: 388

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. For example, a place where I saw a do was in the 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. I have my guesses, but I want them confirmed or denied by someone who knows more than me.

Upvotes: 20

Views: 9755

Answers (3)

sepp2k
sepp2k

Reputation: 370357

do ... end (or alternatively { ... }) creates a so-called block, which is a type of anonymous function in Ruby. In your example that block is passed as an argument to group. group then does some bookkeeping to set the given groups as active, executes the block, and then deactivates the groups again.

Upvotes: 18

Bartłomiej Gładys
Bartłomiej Gładys

Reputation: 4615

It is a block In other programming languages you using brackets, like this: {}. In ruby you can use:

do

  #something code

end

Upvotes: 5

user000001
user000001

Reputation: 33357

The do keyword is used together with the end keyword to delimit a code block.

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

Upvotes: 5

Related Questions