0
0

More than 1 year has passed since last update.

Rubyのクラスについて

Posted at

コード

class Student
 def initialize(name)
  @name = name
 end

 def avg(math, english)
  return @name,(math + english)/2
 end
 
 attr_accessor :name 
end

a001 = Student.new("sato")
p a001.name, a001.avg(30,70)

実行結果

"sato"
["sato", 50]

コード解説

a001 = Student.new("sato")

  • クラス名.new(引数)により、引数を使ってにinitializeメソッドが実行され、インスタンスが生成される
  • インスタンスとはそのクラスに由来するオブジェクト

@name = name

  • @変数はインスタンス変数と呼び、クラス内のどこでも参照できる
  • 何度も使うような変数を定義する

a001.avg(30,70)

  • インスタンス.クラス内で定義したメソッドで処理ができる

attr_accessor :name

  • attr_accessor :インスタンス変数名をクラス内に記述しておくことで、クラスの外でもインスタンス変数を参照できる

a001.name

  • attr_accesorで指定しておいたので、インスタンス.インスタンス変数名で、そのインスタンスが持つインスタンス変数にアクセスできる
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