LoginSignup
1
1

More than 3 years have passed since last update.

クラスとインスタンスを用いたコードの作成

Posted at

クラスとインスタンスを使用して著者、タイトル、本文を出力させたいと考えています。

class Article

  def initialize(author, title, content)
    @author = author
    @title = title
    @content = content
  end

end

#出力結果は
#著者: 鈴木
#タイトル: Hello Ruby!
#本文: こんにちは、Ruby

期待する結果を出力するために、newメソッドを使用して
インスタンスを生成して変数articleに代入します。

article = Article.new("鈴木", "Hello Ruby!", "こんにちは、Ruby")

この時に実引数(("鈴木", "Hello Ruby!", "こんにちは、Ruby"))を指定します。
実引数として指定した値は、仮引数のauthor, title, contentに渡されます。

def initialize(author, title, content)
    @author = author
    @title = title
    @content = content
  end

initializeメソッドで宣言されたインスタンス変数に仮引数に渡された値が代入されます。

インスタンスの値を返すメソッドをそれぞれ定義していきます。

def author
  @author
end

def title
  @title
end

def content
  @content
end

最後に定義したメソッドを呼び出す記述をすれば出力されます。

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("鈴木", "Hello Ruby!", "こんにちは、Ruby")
puts "著者: #{article.author}"
puts "タイトル: #{article.title}"
puts "本文: #{article.content}"

#式展開を使って呼び出します
1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1