Codecabulary Home / Learn Ruby / Blocks

Prefer braces for single lines

	# bad
	names.each do |name|
		puts name
	# good
	names.each { |name| puts name }

Prefer do...end for multiline blocks, control flow, and method definitions:

	# taste
	names.each do |name|
		puts name
		puts "#{ name } is an okay guy."

 Avoid do...end for chaining

# ugly do |name|
	name.start_with?('S') { |name| name.upcase }

# beaut { |name| name.start_with?('S') }.map { |name| name.upcase }

All you can do with a block is associate it with a call to a method via the yield keyword:

	# Define the method
	def a_method
		puts 'Start of method'
		puts 'End of method'
	# Pass a block into the yield statement
	a_method { puts 'In the block' }
	> Start of method
	> In the block
	> In the block
	> End of method

The method and block can have more of a conversation (coroutines) with one another by passing parameters:

	def param_pass
		yield('Bert', 'Hola')
		yield('Dan', 'Sup')
	param_pass { |name, greeting| puts "#{ greeting }, #{ name }!"
	> Hola, Bert!
	> Sup, Dan!