0
0
Rubyprogramming~30 mins

Initialize method as constructor in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Initialize Method as Constructor
📖 Scenario: Imagine you are creating a simple program to keep track of books in a library. Each book has a title and an author.
🎯 Goal: You will build a Ruby class called Book that uses the initialize method as a constructor to set the title and author when a new book is created.
📋 What You'll Learn
Create a class named Book
Add an initialize method that takes two parameters: title and author
Inside initialize, set instance variables @title and @author using the parameters
Create an instance of Book with the title 'The Ruby Way' and author 'Hal Fulton'
Print the book's title and author using the instance variables
💡 Why This Matters
🌍 Real World
Constructors like <code>initialize</code> help set up objects with needed data right when they are created, just like filling out a form when you get a new library card.
💼 Career
Understanding constructors is essential for building classes and objects in Ruby, a key skill for Ruby developers working on web apps, automation, and more.
Progress0 / 4 steps
1
Create the Book class
Create a class called Book with no methods or variables yet.
Ruby
Need a hint?

Use class Book to start the class and end to finish it.

2
Add the initialize method
Inside the Book class, add an initialize method that takes two parameters: title and author. Inside this method, set the instance variables @title and @author to the values of title and author respectively.
Ruby
Need a hint?

Use def initialize(title, author) and set @title = title and @author = author.

3
Create a Book instance
Create a variable called my_book and assign it a new Book object with the title 'The Ruby Way' and author 'Hal Fulton'.
Ruby
Need a hint?

Use my_book = Book.new('The Ruby Way', 'Hal Fulton') to create the book.

4
Print the book details
Print the title and author of my_book using puts and the instance variables @title and @author. Use string interpolation to format the output as: "Title: The Ruby Way, Author: Hal Fulton".
Ruby
Need a hint?

Use puts "Title: #{my_book.instance_variable_get(:@title)}, Author: #{my_book.instance_variable_get(:@author)}" to print the details.