Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Ruby Blocks!
You have completed Ruby Blocks!
Preview
Blocks are easy to use in our classes. In this video, we'll practice writing a class that mimics arrays.
Code Samples
class MyArray
attr_reader :array
def initialize
@array = []
end
def push(item)
array.push(item)
end
def each(&block)
i = 0
while i < array.length
block.call(array[i])
i += 1
end
array
end
end
my_array = MyArray.new
my_array.push(1)
my_array.push(2)
my_array.push(3)
my_array.each{ |item| puts "item: #{item}" }
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
Okay.
So the next thing that we're gonna do
0:00
is take a look at a built in
method by re-implementing it.
0:00
And what we're gonna do
0:04
is create a new class that
functions kind of like an array.
0:06
We're gonna call it my_array.rb.
0:10
So this is going to need to be a class,
MyArray.
0:13
So we'll define the class,
0:18
and we'll have the initialize method,
and for
0:23
right now we're going to
use the built in array.
0:27
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up