I am currently reviewing to train my logical thinking. This time, I will leave it because it was made by a different description method from the model answer.
ruby.rb
class Article
def initialize(author, title, content)
@author = author
@title = title
@content = content
end
end
Add to the above code so that you can get the following output result. However, use classes and instances.
ruby.rb
Author:Yamada
title:How to lose weight correctly
Text:Reduce one meal to 15g of fat and 35g of sugar
ruby.rb
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("Yamada", "How to lose weight correctly", "Reduce one meal to 15g of fat and 35g of sugar")
puts "Author: #{article.author}"
puts "title: #{article.title}"
puts "Text: #{article.content}"
Pass the value to be assigned to the instance variable at the time of instance creation, Define a method to return an instance variable, It's the flow of calling at the end.
The flow is the same, but I also put the characters I want to output in the method.
ruby.rb
class Article
def initialize(author, title, content)
@author = author
@title = title
@content = content
end
def author
puts "Author:#{@author}"
end
def title
puts "title:#{@title}"
end
def content
puts "Text:#{@content}"
end
end
article = Article.new("Yamada", "How to lose weight correctly", "Reduce one meal to 15g of fat and 35g of sugar")
article.author
article.title
article.content
Can this still be done? I'm glad that the hypothesis is correct, I don't know which one is better. I would be grateful if anyone could tell me.
Recommended Posts