LoginSignup
0
0

More than 1 year has passed since last update.

Ruby クラスとインスタンスの概念を使用したコードの記述

Posted at

問題

class Archive

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

end

上記のコードに追加を行い、以下の出力結果を得られるようにしてください。ただし、クラスとインスタンスを使用するものとします。

チャンネル名: Nene Ch.桃鈴ねね
タイトル: 【 #桃鈴ねね3D 】🍑桃鈴ねね3Dお披露目!🍑【ホロライブ/桃鈴ねね】
本文: ホロライブ5期生オレンジ担当、桃鈴ねねです🍑

 回答

class Archive

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

  def name
    @name
  end

  def title
    @title
  end

  def content
    @content
  end

end

archive = Archive.new("Nene Ch.桃鈴ねね", "【 #桃鈴ねね3D 】🍑桃鈴ねね3Dお披露目!🍑【ホロライブ/桃鈴ねね】", "ホロライブ5期生オレンジ担当、桃鈴ねねです🍑")
puts "チャンネル名": #{archive.name}"
puts "タイトル: #{archive.title}"
puts "本文: #{archive.content}"

解説

  def name
    @name
  end

これで@nameというインスタンス変数の宣言。
変数は該当のメソッド、クラス外では使用できないので、

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

にて@name,@title,@contentがある以上、それぞれインスタンス変数を宣言しなければいけない。

archive = Archive.new("Nene Ch.桃鈴ねね", "【 #桃鈴ねね3D 】🍑桃鈴ねね3Dお披露目!🍑【ホロライブ/桃鈴ねね】", "ホロライブ5期生オレンジ担当、桃鈴ねねです🍑")

この部分でArchiveというクラスにて.newメソッドを使用して、インスタンス変数の生成。
この時のname,title,contentはそれぞれ()で記述しているものが格納される。

puts "チャンネル名": #{archive.name}"

最後出力。
変数を文字列として出力したい場合は#{}で記述する。

0
0
0

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
0
0