Ruby クラスとインスタンス
問題
class Article def initialize(author, title, content) @author = author @title = title @content = content end end
こちらのコードを使い下記の結果を出力する問題です。
著者: 阿部 タイトル: Rubyの素晴らしさについて 本文: Awesome Ruby!
自分の回答
class Article def initialize(author, title, content) @author = author @title = title @content = content end def book(name,book,tweet) @name = name @book = book @tweet = tweet puts "#{@author}#{@name}" puts "#{@title}#{@book}" puts "#{@content}#{@tweet}" end end abe_book = Article.new("著者:","タイトル:","本文:") abe_book.book("阿部", "Rubyの素晴らしさについて,","Awesome Ruby!"
模範回答
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("阿部", "Rubyの素晴らしさについて", "Awesome Ruby!") puts "著者: #{article.author}" puts "タイトル: #{article.title}" puts "本文: #{article.content}"
まとめてメゾットを定義するか別々に定義するかの違いですね。
あと著者なども定義しているかしていないかの違いです。