1
1

Ruby Feedback

Last updated at Posted at 2023-02-04

むやみにattr_accessorをpublicに定義するのは好ましくない

外部から書き換えられても良いものには attr_accessorを利用する。
それ以外はattr_readerを使用する

同じ処理は共通化する

vending_machine.rb
- # ペプシを購入するリクエスト
- def request_purchase_pepsi(suica)
-    if suica.deposit >= @pepsi.price
-      @earning += @pepsi.price
-      suica.purchased(@pepsi.price)
-      @pepsi.stock -= 1
-    else
-      puts 'カードの残高が足りません。'
-    end
-  end
-  # モンスターを購入するリクエスト
-  def request_purchase_monster(suica)
-    if suica.deposit >= @monster.price
-      @earning += @monster.price
-      suica.purchased(@monster.price)
-      @monster.stock -= 1
-    else
-      puts 'カードの残高が足りません。'
-    end
-  end
-  # いろはすを購入するリクエスト
-  def request_purchase_irohas(suica)
-    if suica.deposit >= @irohas.price
-      @earning += @irohas.price
-      suica.purchased(@irohas.price)
-      @irohas.stock -= 1
-    else
-      puts 'カードの残高が足りません。'
-    end
-   end

+ # juice_type
+  # 1. ペプシ 2. モンスター 3. いろはす
+  def request_purchase(suica, juice_type)
+    juice_list = [@pepsi, @monster, @irohas]
+    return puts 'カードの残高が足りません。' if suica.deposit < juice_list[juice_type - 1].price
+
+    if juice_list[juice_type - 1].stock.positive?
+      @earning += juice_list[juice_type - 1].price
+      suica.purchased(juice_list[juice_type - 1].price)
+      juice_list[juice_type - 1].stock -= 1
+    else
+      puts "#{juice_list[juice_type - 1].name}の在庫は0です。"
+    end
+  end

早期リターンでif文のネストを少なくする

- if suica.deposit >= juice_list[juice_type - 1].price
-      if juice_list[juice_type - 1].stock.positive?
-        @earning += juice_list[juice_type - 1].price
-        suica.purchased(juice_list[juice_type - 1].price)
-        juice_list[juice_type - 1].stock -= 1
-      else
-        puts "#{juice_list[juice_type - 1].name}の在庫は0です。"
-      end
-    else
-      puts 'カードの残高が足りません。'
-    end

+ return puts "カードの残高が足りません。 " if suica.deposit < juice_list[juice_type - 1].price
+
+ if juice_list[juice_type - 1].stock.positive?
+    @earning += juice_list[juice_type - 1].price
+     suica.purchased(juice_list[juice_type - 1].price)
+     juice_list[juice_type - 1].stock -= 1 
+ else
+    puts "#{juice_list[juice_type - 1].name}の在庫は0です。"
+ end

Rubyのファイル名は小文字で命名する(スネークケース)

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