[Ruby] Summary of class definitions. Master the basics.

[Ruby] Summary of class definitions. Master the basics.

Summary of contents related to class definition of ruby.

table of contents

  1. [Class definition](# class definition)
  2. [Definition of instance variable (attr_accessor :)](#Definition of instance variable attr_accessor-)
  3. [Create Instance (.new)](#Create Instance new)
  4. [Put a value in an instance variable](#Put a value in an instance variable)
  5. [Instance method (method defined in the class)](# instance method method defined in the class)
  6. [Call Instance Method](#Call Instance Method)
  7. [Use instance variables in instance methods (self)](#Use instance variables in instance methods)
  8. [Use if statement in instance method](#Use if statement in instance method)
  9. [initialize method](#initialize method)
  10. [File split (require "")](# File split require-)
  11. [Extract multiple instances individually with each method](# Extract multiple instances individually with each method)
  12. [Add index number to element](# Add index number)
  13. [Receive input value (gets.chomp)](#Receive input value getschomp)
  14. [Convert string to number (.to_i)](#Convert string to number to_i)
  15. Inheritance (<)
  16. [Inheritance file split](# Inheritance file split)
  17. [Add Instance Variable](#Add Instance Variable)
  18. [Add Instance Method](#Add Instance Method)
  19. Override (#override)
  20. [Calling duplicate methods in parent class (super)](#Calling duplicate methods in parent class super)
  21. [Load classes provided by default](#Load classes provided by default)
  22. [Date class](#date class)
  23. [Date class instance method](#date class instance method)
  24. [Check if it is a designated day](#Check if it is a designated day)
  25. [Date class class method](#date class class method)
  26. [Check today's date (.today)](#Check today's date today)
  27. Instance and Class Methods (# Instance and Class Methods)
  28. Create and call class methods (#Create and call class methods)

Class definition

python


class Class name

end

└ Class name is capitalized at the beginning └ No need for ":" at the end of the first line └ "end" is required at the end of the sentence

Instance variable definition (attr_accessor :)

A variable that stores a value that is unique to each instance.

ʻAttr_accessor: instance variable name ` └ Space immediately after attr_accessor └ Symbol (: value) after the space └ No space between ":" and "value"

About the ruby symbol

Definition of instance variables


class Product
  attr_accessor :name
  attr_accessor :price
end

Define instance variables "name" and "price".

Instance creation (.new)

Class name.new

python


class Product
  attr_accessor :name
  attr_accessor :price
end

#Instance generation
product1 = Product.new

Put a value in the instance variable

Instance name. Instance variable name = value

python


class Product
  attr_accessor :name
  attr_accessor :price
end

#Instance generation
product1 = Product.new

#Set a value in an instance variable
product1.name = "iphone"
product1.price = 100000


puts product1.name
puts product1.price

#output
iphone
100000

Set iphone to name of the instance called product1. Set 100000 to price.

Instance method (method defined in the class)

The methods in the class are called instance methods.

python


class class name
def method name(Argument name)
processing
  end
end

Instance method call

instance name.method name

Same as calling an instance variable.

python


class Product
  attr_accessor :name
  attr_accessor :price

  def create
    return "Created an instance(return)"
  end
end

#Instance generation
product1 = Product.new

#Instance method call
puts product1.create


#output
Created an instance(return)

Use instance variables in instance methods

self. Instance variable name

python


class Product
  attr_accessor :name
  attr_accessor :price

  def create
    puts "The product name is#{self.name}is"
    puts "the price is#{self.price}is"
  end
end

#Instance generation
product1 = Product.new

#Set a value in an instance variable
product1.name = "iphone"
product1.price = 100000

#Instance method execution
product1.create


#output
The product name is iphone
The price is 100000

Use an if statement in an instance method

python


class Product
  attr_accessor :name
  attr_accessor :price

  #10% OFF method for orders of 10 or more
  def get_total_price(count)
    total_price = self.price * count
    if count >=10
      total_price *= 0.9
    end
    return total_price
  end
end

#Instance generation
product1 = Product.new

#Set a value in an instance variable
product1.name = "iphone"
product1.price = 100000

#Instance method execution
puts product1.get_total_price(10)

#output
900000

initialize method

A function that is automatically executed when an instance is created. (Constructor such as python)

Pass an argument when creating an instance and set an instance variable.

python


class class name
  def initialize(Argument name)
processing
  end
end

#Instance generation
Instance name=name of the class.new(argument)

▼ Set instance variable with initialize method

Example ①


class Product
  attr_accessor :name
  attr_accessor :price

 def initialize(name,price)
    self.name = name
    self.price = price
 end
 
 def info
   return "product name:#{self.name},price:#{self.price}"
 end

end

#Instance generation
product1 = Product.new("iphone", 100000)

puts product1.info

#output
Product name: iphone, price: 100000

▼ Use keyword arguments

Example ② (keyword argument)


class Product
  attr_accessor :name
  attr_accessor :price

 def initialize(name:,price:)
    self.name = name
    self.price = price
 end
 
 def info
   return "product name:#{self.name},price:#{self.price}"
 end
end

#Instance generation
product1 = Product.new(name:"iphone", price:100000)

puts product1.info


#output
Product name: iphone, price: 100000

File split (require "")

require" ./ filename " ` └ No extension ".rb" required

▼ Read "product.rb" that describes the class definition at the beginning of "index.rb".

product.rb


class Product
  attr_accessor :name
  attr_accessor :price

 def initialize(name:,price:)
    self.name = name
    self.price = price
 end
 
 def info
   return "product name:#{self.name},price:#{self.price}"
 end
end

index.rb


#File reading
require "./product"

#Instantiate with the class of the read file
product1 = Product.new(name:"iphone", price:100000)
puts product1.info

#output
Product name: iphone, price: 100000

Extract multiple instances individually with each method

--File division of class definition and instantiation. --Create multiple instances and store them in an array. --Call each instance one by one with each method. --Execute the info method on each instance.

product.rb


class Product
  attr_accessor :name
  attr_accessor :price

 def initialize(name:,price:)
    self.name = name
    self.price = price
 end
 
 def info
   return "product name:#{self.name},price:#{self.price}"
 end
end

index.rb


#File reading
require "./product"

#Instantiate with the class of the read file
product1 = Product.new(name:"iphone6s", price:60000)
product2 = Product.new(name:"iphone8", price:80000)
product3 = Product.new(name:"iphoneX", price:100000)
product4 = Product.new(name:"iphone11pro", price:120000)

#Store instances in an array
products = [product1,product2, product3, product4]

#Extract instances one by one with each method
products.each do |product|
  #Execute info method on each instance
  puts product.info


#output
Product name: iphone6s, price: 60000
Product name: iphone8, price: 80000
Product name: iphoneX, price: 100000
Product name: iphone11Pro, Price: 120,000

Add index number

--Combine each method with a variable that increments by 1. --Output index number and info method by variable expansion.

index.rb


#File reading
require "./product"

#Instantiate with the class of the read file
product1 = Product.new(name:"iphone6s", price:60000)
product2 = Product.new(name:"iphone8", price:80000)
product3 = Product.new(name:"iphoneX", price:100000)
product4 = Product.new(name:"iphone11pro", price:120000)

#Store instances in an array
products = [product1,product2, product3, product4]

#Define variables for index numbers
index = 0

#Extract instances one by one with each method
products.each do |product|
  #Execute info method on each instance
  puts "#{index}. #{product.info}"
  index += 1

#output
0.Product name: iphone6s, price: 60000
1.Product name: iphone8, price: 80000
2.Product name: iphoneX, price: 100000
3.Product name: iphone11Pro, Price: 120,000

Receiving input values (gets.chomp)

Variable name = gets.chomp

Stores the contents entered before the enter key is pressed in a variable. * Stored as a character string

Convert strings to numbers (.to_i)

Since the information received by gets.chomp is a character string, it is converted to a numerical value. Variable name = gets.chomp.to_i

Receive input data


puts "Please enter a nickname"
name = gets.chomp.to_i

puts "Please enter your age"
age = gets.chomp.to_i

future_age = age+30

puts "#{name}30 years later#{future_age}is"

Receive input value and instance

Receive the instance index number and order quantity.

--Select the instance that corresponds to the received input value. --Receive the order quantity and return the total amount.

▼ Class-defined file

product.rb


class Product
  attr_accessor :name
  attr_accessor :price

 def initialize(name:,price:)
    self.name = name
    self.price = price
 end
 
 def info
   return "product name:#{self.name},price:#{self.price}"
 end
end

index.rb


#File reading
require "./product"

#Instantiate with the class of the read file
product1 = Product.new(name:"iphone6s", price:60000)
product2 = Product.new(name:"iphone8", price:80000)
product3 = Product.new(name:"iphoneX", price:100000)
product4 = Product.new(name:"iphone11pro", price:120000)

#Store instances in an array
products = [product1,product2, product3, product4]

#Define variables for index numbers
index = 0

#Extract instances one by one with each method
products.each do |product|
  #Execute info method on each instance
  puts "#{index}. #{product.info}"
  index += 1

#Receive the item number
puts "Please enter the item number"
order = gets.chomp.to_i

selected_product = products[order]

#Receive the number of orders
puts "The selected product is#{selected_product.name}is"
puts "How many pieces do you want to order?"
count = gets.chomp.to_i

#Calculation of total amount
total_price = selected_product.price * gets.chomp.to_i * 1.1

puts "The total amount is#{total_price}is"

Inheritance (<)

Inherit the instance variables and instance methods of the parent class.

class child class name <parent class name └ Capital letters at the beginning └Finally end required └ Parent class is on top (or read in another file)

Inheritance


require "./File name of parent class"

class child class name<Parent class name

end 

Inheritance file split

Files are roughly classified into four types. Parentheses are examples of file names.

--File that defines the parent class (parent class name.py) --File that defines the child class (child class name.py) --File for instantiation (data.py) --Output file (index.py)

A file that defines child classes is created for each child class. (Depending on the amount of code, it may be combined into one file)

Add instance variable

Simply define a new instance variable in the inherited class.

ʻAttr_accessor: instance variable name `

product.rb


class Product
  attr_accessor :name
  attr_accessor :price

 def initialize(name:,price:)
    self.name = name
    self.price = price
 end
 
 def info
   return "product name:#{self.name},price:#{self.price}"
 end
end

▼ Create Phone class by inheritance. Added instance variable weight.

phone.rb


require "./product"

class Phone < Product
   attr_accessor :weight
end

▼ Set the value to the instance generated by the child class Phone

index.rb


require "./phone"

#Instance generation
phone1 = Phone.new(name: "iphone11", price: "120000")

#Set the value to the added instance variable
phone1.weight = "194g"

puts phone1.weight

#output
194g

Add instance method

Simply define a new instance method in the inherited class.

▼ Added a method to the above phone.rb. self. instance name └ Calling instance variables in a class

phone.rb


require "./product"

class Phone < Product
   attr_accessor :weight

   def set_property
      return "#{self.name}Weighs#{self.weight}is"
   end     
end

▼ Calling additional methods

index.rb


require "./phone"

#Instance generation
phone1 = Phone.new(name: "iphone11", price: "120000")

#Set the value to the added instance variable
phone1.weight = "194g"

#Call the added method
puts phone1.set_property

#output
iphone 11 weighs 194g

override

Overwriting instance variables and methods. (If it is already defined in the parent class, it will be overridden)

product.rb


class Product
  attr_accessor :name
  attr_accessor :price

 def initialize(name:,price:)
    self.name = name
    self.price = price
 end
 
 def info
   return "product name:#{self.name},price:#{self.price}"
 end
end

▼ Override the info method of the parent class

phone.rb


require "./product"

class Phone < Product
   attr_accessor :weight

   #override
   def info
      return "product name:#{self.name},price:#{self.price}Circle, weight:#{self.weight}"
   end     
end

▼ Calling the overridden method

index.rb


require "./phone"

#Instance generation
phone1 = Phone.new(name: "iphone11", price: "120000")

#Set the value to the added instance variable
phone1.weight = "194g"

#Call the added method
puts phone1.info

#output
Product name: iphone11, price: 120,000 yen, weight: 194g

Duplicate method invocation (super) in parent class

Call a method that has already been defined in initialize. super (argument: variable of parent class)

▼ Parent class

product.rb


class Product
  attr_accessor :name
  attr_accessor :price

#Where to call with override
 def initialize(name:,price:)
    self.name = name
    self.price = price
 end
 
 def info
   return "product name:#{self.name},price:#{self.price}"
 end
end

phone.rb


require "./product"

class Phone < Product
   attr_accessor :weight

   #Override of initialize (call existing part)
   def initialize(name:, price:, weight:)
      super(name: name, price: price)      
      self.weight = weight
   end

   #override
   def info
      return "product name:#{self.name},price:#{self.price}Circle, weight:#{self.weight}"
   end     
end

Loading the class provided by default

require" class name " └ Different from reading a file (require "./filename")

Date class

One of the classes defined in Ruby by default. ▼ Loading class require "date"

▼ Date instance generation Variable = Date.new (yyyy, m, d)

▼ Output yyyy-mm-dd

python


require "date"

yesterday = Date.new(2020, 5, 30)
puts yesterday

#output
2020-05-30

Instance method of Date class

Check if it is the specified day of the week

Check if it is the specified day of the week → Return as a boolean value. Instance name.day of the week?

python


require "date"

yesterday = Date.new(2020, 5, 30)
puts yesterday.monday?
puts yesterday.saturday?

#output
false
True

Class method of Date class

Check today's date (.today)

Date.today

python


require "date"

date1 = Date.today
puts date1

#output
2020-05-31

Instance methods and class methods

--Instance method --Call to instance --Instance name.method name --Definition: def method name --End at the end of the sentence

--Class method --Call to class --Class name.Method name --Definition: def class name.method name --End at the end of the sentence

** When using class methods ** -Output results that do not depend on the instance.

Example: Find today's date. Date.today

Creating and calling class methods

You can create your own class methods. def class name.method name

** ▼ Class method to check if today's date is Monday **

--Read Date class --Define class methods

product.rb


require "date"

class Product
  attr_accessor :name
  attr_accessor :price

 def initialize(name:,price:)
    self.name = name
    self.price = price
 end
 
 def info
   return "product name:#{self.name},price:#{self.price}"
 end

#Define class method
 def Product.is_today_off
   today = Date.today
   if today.monday
     "Today is a regular holiday" 
   else
     self.info
end

▼ Use the defined class method

index.rb


require "./product"

product1 = Product.new(name: "iphone11", price: "120000")

#Calling a class method
Product.is_today_off

Recommended Posts

[Ruby] Summary of class definitions. Master the basics.
[Ruby] Class nesting, inheritance, and the basics of self
Basics of Ruby
Docker monitoring-explaining the basics of basics-
[GCD] Basics of DispatchQueue class
Understand the basics of docker
The basics of Swift's TableView
Summary of Java language basics
Summary of Java Math class
[Ruby] Display today's day of the week using Date class
[Summary of technical books] Summary of reading "Learn Docker from the basics"
About the behavior of ruby Hash # ==
About the basics of Android development
Basics of sending Gmail in Ruby
[Ruby] See the essence of ArgumentError
The basics of SpringBoot + MyBatis + MySQL
[Ruby] Date, Time, Datetime class basics
Various methods of the String class
Basics of Ruby ~ Review of confusing parts ~
Ruby Basics 2 ~ Review of confusing parts ~
[Ruby] Display the contents of variables
Summary about the introduction of Device
[Challenge CircleCI from 0] Learn the basics of CircleCI
Ruby basics
Understand the basics of Android Audio Record
Ruby basics
[Ruby] From the basics to the inject method
Now, I've summarized the basics of RecyclerView
part of the syntax of ruby ​​on rails
Summary of hashes and symbols in Ruby
[Ruby basics] About the role of true and break in the while statement
[day: 5] I summarized the basics of Java
[Ruby] Cut off the contents of twitter-ads
Ruby from the perspective of other languages
Looking back on the basics of Java
Ruby basics
[Ruby on Rails] Rails tutorial Chapter 14 Summary of how to implement the status feed
Call a method of the parent class by explicitly specifying the name in Ruby
How to find the cause of the Ruby error
What is JSP? ~ Let's know the basics of JSP !! ~
[Ruby on Rails] Until the introduction of RSpec
[Ruby] Basic knowledge of class instance variables, etc.
[Delete the first letter of the character string] Ruby
I understood the very basics of character input
Recommendation of Service class in Ruby on Rails
The story of introducing Ajax communication to ruby
Manage the version of Ruby itself with rbenv
The basics of the App Store "automatic renewal subscription"
Ruby on Rails ~ Basics of MVC and Router ~
[Ruby] Code to display the day of the week
About next () and nextLine () of the Scanner class
First touch of the Files class (or Java 8)
I checked the number of taxis with Ruby
[Ruby basics] How to use the slice method
Class in Ruby
Ruby syntax summary
[Ruby] Basic code list. Keep the basics with examples
Count the number of occurrences of a string in Ruby
Return the execution result of Service class in ServiceResponse class
[For beginners] DI ~ The basics of DI and DI in Spring ~
[For beginners] Quickly understand the basics of Java 8 Lambda