What Is Block?

A block is just a bit of code that can be executed.

example
1
2
3
4
5
6
[1, 2, 3].each { |num| puts num }

# print
# 1
# 2
# 3
example
1
2
3
4
5
6
7
8
[1, 2, 3].each do |num|
  puts num
end

# print
# 1
# 2
# 3

A block is a piece of code that is declared but not run in the place it’s written. The idea is to run when to call it.

default block using yield
1
2
3
4
5
6
7
8
9
10
11
12
def to_do
  yield
  yield
end

to_do do
  puts "hello"
end

# print
# hello
# hello
block with parameter using yield
1
2
3
4
5
6
7
8
9
10
11
12
def to_do
  yield "bunlong"
  yield "sky"
end

to_do do |name|
  puts "hi, #{name}"
end

# print
# hello, bunlong
# hello, sky
default block using call
1
2
3
4
5
def method_name(&block)
  block.call
end

method_name { puts "hello" } # prints hello
block with parameter using call
1
2
3
4
5
6
7
8
9
10
11
12
def eat(meal, &consume)
  if block_given?
    meal.each {|good| consume.call(good)}
  end
end

puts eat(['cheese', 'steak', 'wine']) {|food| puts 'Hmm, #{food}'}

# prints
# Hmm, cheese
# Hmm, steak
# Hmm, wine