# [Ruby] How to calculate the total amount using the initialize method and class variables

## Overview

There are many ways to get the total amount.

This time, we will use the ** `initialize` method and the`class variable`**.

--Practice --Problem --Conditions (configuration) --Answer (commentary) --Process --Supplement

--Summary --References

## Practice

#### problem

Use the initialize method and class variables to output the total amount of fruit.

#### Condition (configuration)

• name of the class

• Fruits
• 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

@@sum = 0 #Variable definition

def initialize(name, price) #name as an argument in the initialize method,Receive price
@name  = name             #Instance [email protected] name
@price = price            #Instance [email protected] 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!
``````

#### process

1. Instance generation

--Pass arguments into the class --`initialize` is called

2.`initialize`

--Instance variable definition --Add `price` of each fruit to` @@ sum`

1. Define a method so that it can be output to the terminal

2. Method call

#### Supplement

--You can use instance variables without @ by using `attr_reader`. (In code, ** name and price ** of ** cost method **)

## Summary

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