coding for food
[Ruby] Ruby class // initialized method
silveryen
2022. 8. 26. 02:14
class Book #created my own data type and a template for what a book is
attr_accessor :title, :author, :pages
end
book1 = Book.new() #creating book object
book1.title = "Harry Potter"
book1.author = "JK Rowling"
book1.pages = 400
puts book1.title
여러번 쓰는 것을 initialized method를 이용해서 간결하게 쓸 수 있다.
class Book
attr_accessor :title, :author, :pages
def initialize(title, author, pages)
@title = title
@author = author
@pages = pages
end
end
book1 = Book.new("Harry Potter", "JK Rowling", 400)
book2 = Book.new("Load of the Ring", "Tolkein", 500)
puts book1.author # => JK Rowling