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.
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With