Um momento
0x50Lesson 6 of 6

Build methods and simple classes

Write reusable methods and model objects with classes.

13 min 4-question quiz 1 code exercise
By the end of this lesson you can
  • Define and call a method and initialize an object.

A method names reusable behavior. Parameters follow the method name, and def/end mark the method body. A class describes objects with shared behavior. initialize runs when an object is created with new, and attr_reader provides a readable accessor for an instance variable.

main.rb
1class Greeter
2  def initialize(name)
3    @name = name
4  end
5
6  def greeting
7    "Hello, #{@name}!"
8  end
9end
10
11puts Greeter.new("Ruby").greeting
Output
Hello, Ruby!

An instance variable begins with @ and belongs to one object. In Ruby, the last expression in a method is returned automatically, though using return is also allowed. Objects let related data and behavior live together.

Key takeaways

  • Define and call a method and initialize an object.

  • Ruby methods and blocks help express operations clearly.

  • Read each result and error message as feedback about your code.

Lesson quiz

4 questions · pass with 3 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Ruby

Write Ruby in the editor and run it against sample input. Your code is sent to Wandbox to run.

Exercise 1

Create a rectangle

+25 XP

Complete the Rectangle class so it stores width and height and has an area method. Read both values and print the area.

  • Three by four
  • Five by two
main.rb
Loading editor…

Ruby runs through Wandbox, a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: