LoginSignup
1
0

More than 3 years have passed since last update.

Ruby クラスとインスタンスの作成

Posted at

クラスの作成

オブジェクトはクラスから作成されます。
クラスからオブジェクトを作成することをインスタンス化といいます。

実際にクラスを作成していきます。
以下のように、class構文を使用します。

sample.rb
class House
end

クラス名の先頭は大文字にする規則があります。
この記述で、最小限のHouseクラスを定義できました。

インスタンス化

次は、作成したHouseクラスからインスタンス(オブジェクト)を作成していきます。
newメソッドを使用することで、インスタンス(オブジェクト)を作成できます。

sample.rb
class House
end
House.new

クラスを呼び出すためには、クラス名を記述します。

sample.rb
class House
end
House

インスタンス(オブジェクト)のクラス

インスタンスのクラスがHouseクラスであることを確認してみます。

sample.rb
class House
end

puts House.new.class

コンソール上で、sample.rbを実行し、以下のように出力されていれば正しくインスタンスが、Houseクラスから作成できています。

House
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