There are many ways to get the total amount.
This time, we will use the ** initialize
method and theclass variable
**.
--Practice --Problem --Conditions (configuration) --Answer (commentary) --Process --Supplement
--Summary --References
Use the initialize method and class variables to output the total amount of fruit.
name of the class
instance
apple --Name: Apple --Price: 200
banana --Name: Banana --Price: 150
melon --Name: Melon --Price: 500
--Class variables - sum
--Class method - get_sum
--Instance variables - name - price
Answer example
class Fruits
attr_reader :name, :price #Make it readable
@@sum = 0 #Variable definition
def initialize(name, price) #name as an argument in the initialize method,Receive price
@name = name #Instance variables@define name
@price = price #Instance variables@Define price
@@sum += price # @@Add the total amount of each fruit to sum
end
#Fruit name and price
def cost
puts "#{name}The price of#{price}It is a circle."
end
#Total amount of fruit
def self.get_sum
puts "The total price is#{@@sum}It's a yen!"
end
end
#Instance generation
apple = Fruits.new('Apple', 200)
banana = Fruits.new('banana', 150)
melon = Fruits.new('melon', 500)
#call
apple.cost
banana.cost
melon.cost
Fruits.get_sum
#Terminal output result
#The price of an apple is 200 yen.
#The price of bananas is 150 yen.
#The price of melon is 500 yen.
#The total price is 850 yen!
--Pass arguments into the class
--initialize
is called
2.initialize
--Instance variable definition
--Add price
of each fruit to @@ sum
Define a method so that it can be output to the terminal
Method call
--You can use instance variables without @ by using attr_reader
. (In code, ** name and price ** of ** cost method **)
--initialize
is called when instantiating
--Class variables can be defined by prefixing the variable with @@
--Getter methods can be defined by using attr_reader
--Setter methods can be defined by using attr_writer
--Getter / setter methods can define both by using attr_accessor
-Ruby 3.0.0 Reference Manual (Variables and Constants) -[Ruby] attr_accessor method beginner's guide ~ Let's understand how to use and why it is necessary -[Ruby] Understanding "getters" and "setters" -About ruby variables