I am learning programming. This is the first post. I hope that by writing what I have learned, I will be able to establish myself more. I look forward to working with you.
I will get into the main subject immediately.
I took a little time to answer the Ruby problem that came up at a certain programming school, so I will make a note so that I will not forget it. It's a very rudimentary problem, but ... The question and the correct answer are as follows (I'm not happy if the content of the question is the same, so I've changed it a little).
class Article
def initialize(author, title, content)
@author = author
@title = title
@content = content
end
end
#Use classes and instances to add to the above code so that you get the following output
The author:Suzuki
title:Nice to meet you
Text:This is the first post
class Article
def initialize(author, title, content) #3rd line
@author = author
@title = title
@content = content
end
def author #9th line
@author
end
def title #13th line
@title
end
def content #17th line
@content
end
end
article1 = Article.new("Suzuki", "Nice to meet you", "This is the first post") #Line 23
puts "The author: #{article1.author}" #25th line
puts "title: #{article1.title}"
puts "Text: #{article1.content}"
First of all, hold down the following
Learn more about each line
(Lines 3-7)
In the instance variable defined in the initialize method, assign the three values received as arguments, Suzuki,Nice to meet you, and First post, to each instance variable.
(Lines 9-19)
Define each instance method to return the value of the instance variable.
Of course, for example, if you write @ author instead of ʻarticle1.author on the 25th line without defining these instance methods, Suzuki` will not be output.
(Line 23)
Create an instance of the Article class and assign it to the variable article1.
At that time, the three values Suzuki, Nice to meet you, and First post are passed as actual arguments to the formal arguments ʻauthor, title, and content`, respectively.
(Lines 25-27)
Call the instance method defined in lines 9-19.
Instance methods can be called with instance name.method name.
I think this article has helped me remember about classes and instances. It was a good opportunity. I will write if something happens again.
Thank you to everyone who has been with us so far.
Recommended Posts