0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

今日はインスタンスメソッドを学んでみた!

image.png

今日の学び

クラスの中で定義したメソッドの使い方

  • クラスの中でメソッドを定義でき、「インスタンス.メソッド名」で呼び出せる
      • class Menu
      • attr_accessor :name
      • attr_accessor :price
      • def show
      • puts "私はメニューです"
      • end
      • end
      • menu1 = Menu.new
      • puts menu1.show
  • インスタンスメソッドも引数を受け取ったり戻り値を返すことができる
      • class Menu
      • attr_accessor :name
      • attr_accessor :price
      • def show(data)
      • return "私は#{data}です"
      • end
      • end
      • menu1 = Menu.new
      • puts menu1.show("メニュー")

インスタンスメソッドの中でインスタンス変数を使う方法

  • インスタンスメソッドの中で「self.変数名」を使うことでインスタンス変数を使える
      • class Menu
      • attr_accessor :name
      • attr_accessor :price
      • def show_name
      • return "私は#{self.name}です"
      • end
      • end
      • menu1 = Menu.new
      • menu1.name = "ピザ"
      • menu1.show
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?