Block Party - Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

Block Party

We're going to invite some procs and lambdas into our discussion. However, we need to cover some more on blocks in order to prepare. Recall some block syntax.

ary = [1, 2, 3, 4]

ary.each { |num| puts num + 10 }

11

12

13

14

Remember that num is the name we made up for our local variable. It can only be accessed from within the block. The block is what's in the curly braces.

Yield

Methods that accept blocks give control to the calling method.

def method

puts "In the method."

yield

puts "In the method."

end

method {puts "In the calling method block."}

In the method.

In the calling method block.

In the method.

We can also yield to parameters.

def method(para)

yield("Ruby")

yield(para)

end

method("Python") { |x| puts "I like #{x}." }

I like Ruby.

I like Python.

Breaking it down:

def method(para)

yield("Ruby") #Overrides calling method's argument.

yield(para) #Uses calling method's argument.

end

method("Python") { |x| puts "I like #{x}." }

I like Ruby. #1st yield. Uses "Ruby" for x.

I like Python. #2nd yield. Uses "Python" for x.

Procs

Suppose we wanted to create a block and pass it around like a variable or method. Using the logic from earlier, we'd think this is the way to do it:

block = { |v| puts v } #This is no good.

One way to turn a block into an object is to create a proc out of it.

block = Proc.new { |v| puts v }

We've just created a proc that's called block. All we need to do is use the call method on the proc now.

block.call "Victory!"

Victory!

We can now use our block as argument in a method. We do this by adding an ampersand & to the front of our proc name. In the following example we will create a proc and then use it with the method select.

Create two arrays that represent people's ages.

people_one = [54, 21, 45, 76, 12, 11, 67, 5]

people_two = [21, 54, 65, 32, 65, 87, 21, 12]

Now we will create two procs that specify an age range.

over_thirty = Proc.new { |age| age >= 30 }

over_twenty_one = Proc.new { |age| age >= 21 }

Now we will create new variables that are equal to the age selections of people_one and people_two when our procs are used with select.

group_one = people_one.select(&over_thirty)

group_two = people_two.select(&over_twenty_one)

print group_one

print group_two

[54, 45, 76, 67][21, 54, 65, 32, 65, 87, 21]