** Class variables ** ・ Sum
** Instance variable ** ・ Name ・ Price
** Class methods ** ・ Get_sum ↪️ "The total price is" class variable sum "yen" is displayed
** Instance method ** ・ Initialize ↪️ Pass the name and price as arguments and assign them to the instance variables name and price Add price to sum
After defining, let's create the following three instances from the class Fruits
instance
Instance name | name | price |
---|---|---|
apple | Apple | 120 |
orange | Orange | 200 |
strawberry | Strawberry | 60 |
** Template ** The template of the program to be made is as follows.
class Fruits
#Add the class definition here
end
#Create 3 instances below
#Once generated, get the class method_Let's call sum to display the total price
(1) First, define the class Fruits, and then define the class variable ** sum ** and the class method ** get_sum **.
(2) Next, define the instance variables name and price in the initialize method. The initialize method can receive the arguments of the new method. Receive the name and price from the new method and assign it to the instance variable. Then, add the price argument price received by the initialize method to the class variable "** @@ sum **".
(3) Pass the name and price as arguments when creating an instance with the new method.
④ Call ** get_sum ** to complete.
class Fruits
@@sum = 0
def self.get_sum
puts "The total price is#{@@sum}It's a yen"
end
def initialize(name, price)
@name = name
@price = price
@@sum = @@sum + price
end
end
apple = Fruits.new("Apple", 120)
orange = Fruits.new("Orange", 200)
strawberry = Fruits.new("Strawberry", 60)
Fruits.get_sum
Recommended Posts