[Ruby] initialize method

Progate learning notes The initialize method is called immediately after the instance is created

Initialize method with no arguments

class Menu
attr_accessor :name
attr_accessor :price

  #Called after the menu instance is created
  def initialize
    self.name = "soup" # インスタンス変数nameにsoupという情報が入る
    self.price = 500 #The instance variable price contains the information 500
  end

  def info
    return "#{self.name}: ¥#{self.price}"
  end
end

#A menu instance is created from the Menu class
menu = Menu.new
puts menu.info

result

soup: ¥500

Initialize method with arguments

class Menu
attr_accessor :name
attr_accessor :price

  def initialize(name:, price:)
    self.name = name
    self.price = price
  end

  def info
    return "#{self.name}: ¥#{self.price}"
  end
end

#Set the information in the argument of initialize method here
menu = Menu.new(name:"curry", price:850)
puts menu.info

result

curry: ¥850

Reference: Progate

Recommended Posts

[Ruby] initialize method
Ruby Learning # 30 Initialize Method
initialize method
Ruby to_s method
[Ruby] slice method
[Ruby] end_with? method
[Ruby] Method memorandum
Ruby build method
Ruby accessor method
ruby map method
abbreviation for ruby method
Ruby Learning # 24 Exponent Method
definition of ruby method
[Ruby] Method definition summary
Method
Ruby algorithm (inject, method definition)
[Ruby] Notes on gets method
[Ruby] Method that returns truth
[ruby] Method call with argument
What is the initialize method?
Ruby design pattern template method pattern memo
[Ruby] Method to count specific characters
[Ruby] present/blank method and postfix if.
[Ruby] Extracting elements with slice method
[Ruby basics] split method and to_s method
[Ruby] How to use any? Method
About the role of the initialize method
[Ruby] Search problem using index method
[Ruby on Rails] Convenient helper method
[Ruby] undefined method `dark?'occurs in rqr_code
How to use Ruby inject method
Ruby learning 4
[Ruby] Array
Java method
[Ruby] Obtaining even values ​​using the even? Method
to_i method
Ruby learning 5
Ruby basics
java (method)
Ruby Review 2
getRequestDispatcher () method
Ruby addition
Refactoring Ruby
Ruby on Rails installation method [Mac edition]
Ruby learning 3
Implemented "Floyd Cycle Detection Method" in Ruby
Map method
include method
Abstract method
Ruby print puts p printf output method
List method
puts method
Ruby setting 2
ruby Exercise Memo II (variable and method)
Java method
Class method
Ruby problem ⑦
save! method
Ruby learning 2
[Java] method
[Ruby] Block