Day 7: Iterators and Inheritance

Iterators

Iterators make you life as a developer easier. It’s like while loop construct, but you don’t have to worry about an exiting condition. Isn’t it awesome? Check it out:

Loop vs Iterator

Look at how we rewrote the example with an Olympic runner. Now we’ve used the most common Ruby iterator named each. This is a builtin method on any array or a hash.

Iterator goes over each element of an array. It passes one element at the time through a block of code.

The code in between the keywords do and end is called a code block.

In order to use an iterator, you need to call the method each. Then you start passing it a block using the keyword do. Next, you specify the variable name surrounded by two pipe signs. This variable will represent an individual element of the array. You can use this variable inside a code block. After you finish writing code inside the block, you can close it by using the keyword end.

It’s important to note here is that you don’t need to track when to stop. Code inside the block will be automatically executed the same number of times as many elements we have in an array.

Inheritance

Inheritance is a way to describe a relationship between classes. If one of parents is good at sports, their child might become good at sports too. It’s because the child inherited those skills from it’s parent. Let’s code it up:

class Parent
  def play_sports
    puts "Ready, set, go!"
  end
end

Here is our Parent class that has one method called play_sports. Any instance of Parent class has the method play_sports. You can try it in IRB.

>> parent_instance = Parent.new
>> parent_instance.play_sports
Ready, set, go!

Now we’re going to write the class called Child which inherits from our Parent.

class Child < Parent
end

Use < sign after the name of the child class followed by the parent class name. The class on the left side of < sign is called a child class. The class on the right side is called a parent class or a base class. Let’s instantiate a Child class. Maybe it can play sports too.

>> child_class = Child.new
>> child_class.play_sports
Ready, set, go!

Yes, it can. Because it inherited play_sports method from it’s parent.

Inheritance is very powerful. As soon as you inherit your child class from a base class, the parent class becomes a part of the child class. It is very useful if you want to reuse parent’s class methods in your child class.

Photo by fdecomite