1
0

Rubyの基本(クラス・インスタンス)

Last updated at Posted at 2024-03-02

クラスの定義

「クラス」とは、関連する変数やメソッドをまとめて、複雑なデータを扱いやすくするための仕組みである。
クラスの定義通りに作ったデータを、そのクラスの「インスタンス」と呼ぶ。
クラスは設計書、インスタンスは設計書を元に作られたものであるといえる。

sample_01.rb
# クラスの定義
class User
  def get_info
    "user name and score here"
  end
end

# インスタンスの生成
user1 = User.new
user2 = User.new

# インスタンスメソッドの呼び出し
puts user1.get_info
puts user2.get_info
# user name and score here
# user name and score here

initializeメソッド(イニシャライザ)

initializeメソッド(イニシャライザ)とは、インスタンス生成と同時に呼び出せる特殊なメソッドである。
以下に使い方の一例を示す。

sample_02_01.rb
class User

  attr_accessor :name, :score

  def initialize(name, score)
    self.name = name
    self.score = score
  end

  def get_info
    "#{self.name} #{self.score}"
  end
end

user1 = User.new("Taro", 70)
user2 = User.new("Jiro", 90)

puts user1.get_info # Taro 70
puts user2.get_info # Jiro 90

上記の例では、メソッドの外側でインスタンス変数を定義し、selfを使ってインスタンスメソッドの中で使える
ようにした。

インスタンス変数の定義方法は他にもあり、@を使うことでインスタンスメソッドの中でインスタンス変数を定義することもできる。
以下に一例を示す。

sample_02_02.rb
class User

  def initialize(name, score)
    @name = name
    @score = score
  end

  def get_info
    "#{@name} #{@score}"
  end
end

user1 = User.new("Taro", 70)
user2 = User.new("Jiro", 90)
puts user1.get_info
puts user2.get_info

インスタンス変数へのアクセス

インスタンスから実行できるのはインスタンスメソッドのみで、インスタンス変数は実行できない。
インスタンスから変数にアクセスする場合は、そのためのインスタンスメソッドを定義する必要がある。
また、インスタンスからインスタンス変数を更新する場合は、別にそのためのインスタンスメソッドを定義する必要がある。
インスタンスからインスタンス変数にアクセスするためのインスタンスメソッドを「getter」、インスタンスから インスタンス変数を更新するためのインスタンスメソッドを「setter」と呼ぶ。

sample_03.rb
class User
  def initialize(name, score)
    @name = name
    @score = score
  end

# getter
  def name
    @name
  end

# setter
  def name=(new_name)
    @name = new_name
  end

  def get_info
    "Name: #{@name}, Score: #{@score}"
  end
end

user1 = User.new("Taro", 70)
user2 = User.new("Jiro", 90)

# インスタンス変数の更新
user1.name = "TARO"

puts user1.name # TARO

「sample_02_01.rb」において、attr_accessorを使ってインスタンス変数を定義したが、これによって「getter」と「setter」の両方を定義したことと同じことになる。

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