LoginSignup
0
0

More than 3 years have passed since last update.

rubyクラスを利用したアプリ

Last updated at Posted at 2020-11-20

シンボルクラスとストリングクラスは同義と考える
hash = {"key" => "value"}
hash = {key: => "value"}

教訓

1.attr_accessor :id, :name, :content クラス外から参照、編集するために必要な処理
2. @@xxxはクラス変数。クラスを使うたびに定義される
3. @xxxはインスタンス変数。インスタンス毎に定義される
4. @tasks << task(TASKクラスを利用したインスタンス)ではインスタンス変数に、task(TASKクラスを利用したインスタンス)を配列の要素として代入している。※ハッシュを代入していると思っており、ハッシュのメソッドを探していた。
5. initializeはインスタンス作成時に動作する(主に変数の初期値設定)
6. クラス毎に用途を分けた方が良い。今回なら、TASKクラスはタスクを保存するため用途。TODOクラスはtaskインスタンスを扱う用途。

class Task
  # コードを追加
  attr_accessor :id, :name, :content
  @@count = 0

  def initialize(**params)
    @name = params[:name]
    @content = params[:content]
    @id = @@count += 1
  end

  def info
    "タスクNo.#{@id} : #{@name} #{@content}"
  end
end

class Todo
  # コードを追加
  # initializeはインスタンス作成時に動くから、作成時にインスタンス変数等に引数を代入したい時に引数を定義する
  # 今回の場合は空配列を初期化するために実装しただけなので、引数を定義していない
  def initialize
    @tasks = []
  end

  # 作成後のインスタンスごとに引数を渡しながらメソッドを動作させるときはあらかじめ引数を用意しておく
  def add(task)
    @tasks << task
  end

  def info
    @tasks.each do |todoList|
      puts todoList.info 
    end
  end
-----------ここをid:にどうやってtodoList.delete(id:1)の値を入れ込むかわからなくて苦労した。----
  def delete(id:)
    delete_task = @tasks.find { |task| task.id == id }
    @tasks.delete(delete_task)
  end
end
---------------------------------------------------------------------------------
task1 = Task.new(name: "洗濯", content: "8時までに干し終える")
task2 = Task.new(name: "仕事", content: "9時〜18時")
task3 = Task.new(name: "買物", content: "卵,ネギ")

todoList = Todo.new
todoList.add(task1)
todoList.add(task2)
todoList.add(task3)
todoList.info
puts "----"
todoList.delete(id:1)
todoList.info

0
0
1

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