Ruby Intermediate Introduction
This course goes deeper into Ruby. It builds on the beginner course, where you met blocks, modules and classes.
A beginner loop, revisited
An each loop walks a list one item at a time. Each item prints on its own line.
scores = [70, 85, 90]
scores.each do |score|
puts score
endA module mixed into a class
Greeter holds one greet method. Dog mixes Greeter in with include, so a dog object can call greet.
module Greeter
def greet
puts "Hello from the module"
end
end
class Dog
include Greeter
end
dog = Dog.new
dog.greetA plain class at work
Box stores one label when it is built. The label method hands that label back.
class Box
def initialize(label)
@label = label
end
def label
@label
end
end
box = Box.new("tools")
puts box.labelExample
module Tagger
def tag
puts "Item: #{@name}"
end
end
class Crate
include Tagger
def initialize(name)
@name = name
end
def pack(items)
items.each do |item|
puts "Packing #{item}"
end
end
end
crate = Crate.new("Kitchen crate")
crate.tag
crate.pack(["cups", "plates"])Key points
- Blocks can take values and can be stored for later.
- Modules mix shared methods into classes.
- Classes follow fixed rules when they look a method up.
- Files and errors get a fuller treatment in this course.
- Every program here still runs as one file with ruby main.rb.
In this example, Crate mixes in the Tagger module and gains the tag method. The pack method takes a list and runs a block for each item. The tag line prints first, and then each packing line prints in list order.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does include do inside a class?