[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 theclass variable**.

table of contents

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

--Class variables - sum

--Class method - get_sum

--Instance variables - name - price

Answer (commentary)

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!

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

References

-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

Recommended Posts

[Ruby] How to calculate the total amount using the initialize method and class variables
Easy to understand the difference between Ruby instance method and class method.
[Ruby] How to use gsub method and sub method
How to find the total score and average score
[Ruby basics] How to use the slice method
How to operate IGV using socket communication, and the story of making a Ruby Gem using that method
Use hashes well in Ruby to calculate the total amount of an order
How to create and execute method, Proc, Method class objects
[Ruby] How to get the tens place and the ones place
How to get the class name / method name running in Java
How to set and describe environment variables using Rails zsh
How to use the form_with method
How to use the wrapper class
[Ruby] How to use any? Method
How to use Ruby inject method
How to POST JSON in Java-Method using OkHttp3 and method using HttpUrlConnection-
[Ruby] Obtaining even values ​​using the even? Method
[Ruby on Rails] How to log in with only your name and password using the gem devise
[Android] How to turn the Notification panel on and off using StatusBarManager
How to create a query using variables in GraphQL [Using Ruby on Rails]
[Java] How to use the HashMap class
[Java] How to calculate age using LocalDate
[Java] How to use the toString () method
[Processing × Java] How to use the class
[Java] How to get to the front of a specific string using the String class
How to find the tens and ones
Iterative processing of Ruby using each method (find the sum from 1 to 10)
[Easy] How to upgrade Ruby and bundler
[Java] How to use the Calendar class
[Ruby On Rails] How to search the contents of params using include?
If it is Ruby, it is efficient to make it a method and stock the processing.
[Ruby] Learn how to use odd? Even? And count the even and odd numbers in the array!
[JDBC ③] I tried to input from the main method using placeholders and arguments.
How to find the cause of the Ruby error
How to output Excel and PDF using Excella
[Java] How to use FileReader class and BufferedReader class
How to execute and mock methods using JUnit
How to play audio and music using javascript
How to implement the breadcrumb function using gretel
Output of how to use the slice method
How to use the replace () method (Java Silver)
Ruby: Differences between class methods and instance methods, class variables and instance variables
How to build the simplest blockchain in Ruby
[Ruby on Rails] How to use session method
Ruby How to convert between uppercase and lowercase
[Java] How to use Calendar class and Date class
[Ruby] How to use the map method. How to process the value of an object and get it by hash or symbol.
[Ruby] initialize method
How to get the class name of the argument of LoggerFactory.getLogger when using SLF4J in Java
[ruby] How to assign a value to a hash by referring to the value and key of another hash
[Rails] How to solve the error "undefined method` visit'" when using Capybara with Rspec
[Java] How to use compareTo method of Date class
[Ruby] Cut out a string using the slice method
Examine the elements in the array using the [Ruby] includes? Method
[Ruby] How to find the sum of each digit
How to add characters to display when using link_to method
[Ruby on Rails] How to change the column name
Bind the request to any class and receive it
How to convert A to a and a to A using AND and OR in Java
How to handle TSV files and CSV files in Ruby
I want to call the main method using reflection