I want to output the author, title, and body using classes and instances.
class Article
def initialize(author, title, content)
@author = author
@title = title
@content = content
end
end
#The output result is
#Author:Suzuki
#title: Hello Ruby!
#Text:Hello, Ruby
Use the new method to output the expected result Create an instance and assign it to the variable article.
article = Article.new("Suzuki", "Hello Ruby!", "Hello, Ruby")
Actual argument at this time (( "Suzuki", "Hello Ruby!", "Hello, Ruby")) to specify the. The value specified as the actual argument is passed to the formal arguments author, title, and content.
def initialize(author, title, content)
@author = author
@title = title
@content = content
end
The value passed to the formal argument is assigned to the instance variable declared by the initialize method.
We will define each method that returns the value of the instance.
def author
@author
end
def title
@title
end
def content
@content
end
It will be output if you write a description that calls the method defined last.
class Article
def initialize(author, title, content)
@author = author
@title = title
@content = content
end
def author
@author
end
def title
@title
end
def content
@content
end
end
article = Article.new("Suzuki", "Hello Ruby!", "Hello, Ruby")
puts "Author: #{article.author}"
puts "title: #{article.title}"
puts "Text: #{article.content}"
#Call using expression expansion
Recommended Posts