Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 390
Miika Vuorio Avatar asked Sep 10 '16 15:09

Miika Vuorio


People also ask

What is do keyword in Ruby?

The do keyword comes into play when defining an argument for a multi-line Ruby block. Ruby blocks are anonymous functions that are enclosed in a do-end statement or curly braces {} . Usually, they are enclosed in a do-end statement if the block spans through multiple lines and {} if it's a single line block.

What is do end Ruby?

There are two ways of defining a block in Ruby: The first is using the do.. end keyword, the other is using a pair of curly braces. Do.. end block is mainly used when defining a block of code that spans multiple lines, while curly braces {} are used when defining a block of code that spans a single line.

What does yield do in Ruby?

yield tells ruby to call the block passed to the method, giving it its argument. yield will produce an error if the method wasn't called with a block where as return statement don't produces error.

What does .first mean in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.


2 Answers

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.

like image 177
sepp2k Avatar answered Sep 22 '22 22:09

sepp2k


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

like image 37
user000001 Avatar answered Sep 21 '22 22:09

user000001