Introduction to Ruby basic grammar with yakiniku

About this article

This is a memo for learning content output and self-reflection by beginners introductory to Ruby basic grammar. The value is mostly yakiniku for fun notes.

** References ** Progate Ruby Learning Course Introduction to Dot Installation Ruby

[Character string]

String

--"": Special characters and expression expansion can be used --"'": The value is output as it is --"\ n": Line break --"\ t": Show tab -"* Numerical value": Display the number of numerical values

The method that came out during string learning

learning.rb


price.upcase #Returns a string in uppercase
price.upcase! #Rewrite the original string to uppercase while returning the string in uppercase
price.reberse #Returns the string in reverse order
price.emyty? #Check if the string is empty
price.include?("t") #Find out if a particular character is included

[Numeric value]

learning.rb


p 10 + 3 # 13
p 10 * 3 # 30
p 2.4 * 2 # 4.8
p 10 / 3 # 3
p 10.0 / 3 # 3.33333...(Show after the decimal point)
p 10 % 3 # 1
p Rational(2, 5) + Rational(3, 4) #(Fraction 23/20)
p 2/5r + 3/4r #(Abbreviation for fractional Rational)

p 52.6.round #Rounding
p 52.6.floor #Truncate after the decimal point
p 52.6.ceil #Round up after the decimal point

【comment】

--If you write "#" at the beginning of a line, that line becomes a comment. -All lines enclosed by = begin ~ = end are comments

learning.rb


#I haven't eaten yakiniku, so I don't understand much from the instance variables.

=begin
So calmly organize the information and refer to other articles
Deepen your understanding or eat yakiniku ry
=end

[Difference in output]

"P" is displayed surrounded by double quotation marks In the case of a complicated structure, this will be displayed as a character string so that it is easy to understand.

learning.rb


print "Do you like Yakiniku?" #Output without line breaks
puts "Do you like Yakiniku?" #Output with line breaks
p "Do you like Yakiniku?" #For debugging

【conversion】

Number and character conversion

learning.rb



p 29 + "29".to_i #Convert to integer "too integer" to_i
p 29 + "29".to_f #Convert to floating point number "to float" to_f
p 29.to_s + "29" #Return to string "String" to_s

Hash and array return

learning.rb


# t_a (to Array)Convert hash to array
# to_ #h(to Hash)Convert array to hash

price = {Upper tongue: 1800,Upper skirt steak: 1500}
p price.to_a.to_h

【%notation】

learning.rb


puts %Q(hello) #""Represent the character string enclosed in
puts %(hello) #The above Q can be omitted
puts %q(hello) #''Represent the character string enclosed in

Why use% notation?

If you want to use "'in" "" or "''" It is necessary to add "" to mean that it is not a delimiter % Notation is not required and may be easier to read

learning.rb


puts "he\"llo"  puts %(hello)
puts 'he\'llo'  puts %q(hello)

% Notation when you want to manage strings in an array

If you write a lot of values, you can also write like this

learning.rb


p ["red", "blue"]  p %W(red blue)
p ['red', 'blue']  p %w(red blue)

[Embed value in string with formatting]

** "string"% value ** Display various values ​​with formatting

--% s: string --% d: Integer --% f: Floating point number

String

learning.rb


p "name: %s" % "Aged ribs"
p "name: %10s" % "Aged ribs" #Secure a width of 10 digits
p "name: %-10" % "Aged ribs" #Secure 10 digits + left justified

Numerical value

learning.rb


p "id: %05d, rate: %10.2f" % [29, 2,929]
#If there are multiple values, pass them as an array
#If id is an integer and rate is a floating point number
#I want the id to be 5 digits, but if it is less than 5 digits, fill it with 0
#The rate has 10 digits before the decimal point and 2 digits after the decimal point.

printf/Sprintf printf Instructions for displaying a formatted string

learning.rb


printf("name: %10s\n", "taguchi")
printf("id: %05d, rate: %10.2f\n", 355, 3.284)

Sprintf A command that returns a string instead of displaying it Since the character string is returned, display it with p

learning.rb


p sprintf("name: %10s\n", "taguchi")
p sprintf("id: %05d, rate: %10.2f\n", 355, 3.284)

[Array]

learning.rb


colors = ["red", "blue", "yellow"]

p colors[0] #Subscript(Start from 0)Output
p colors[-1] #Outputs the subscript (1 at the end) counted from the end
p colors[0..2] #Output 0 to 2
p colors[0...2] #Output 0 to 1 (until just before 2)
p colors[5] #nil (nothing)

colors[0] = "pink" #Change the value of the specified subscript
colors[1..2] = ["white", "black"] #Change the specified numbers at once
colors.push("gold") #Add value to the end
colors << "silver" #Abbreviation to add a value at the end

The method that came out during array learning

learning.rb


p colors.size #Indicates the number of elements
p colors.sort #Sorts the elements

【hash】

How to manage multiple values ​​at once by pairing keys and values ​​(object)

Difference between array and hash

** Array **: Manage multiple values ​​side by side ** Hash **: Manage each value with a name called a key

Arrays enclose elements in [], but hashes in {} {Key 1 => Value 1, Key 2 => Value 2}

Connect the key and value with "=>" Like arrays, elements are separated by commas (,)

learning.rb


prices = {"bibimbap" => 800, "gukbap" => 700}

Symbol object

Objects like identifiers starting with: "Symbol object" is often used as the key It's faster than using strings and is often used in Ruby.

learning.rb


prices = {:bibimbap => 800, :gukbap => 700}

Hashes using the above symbols are often used, so there is a short notation.

learning.rb


prices = {bibimbap: 800, gukbap:700}

Access to each hash element is the same as an array

learning.rb


p prices[:bibimbap] #Use symbols

Update hash elements

learning.rb


prises[:bibimbap] = 900 #update

Add hash element Add element by writing hash [new key] = value Note that if you specify an existing key, it will be updated instead of adding an element.

learning.rb


prices[:Namul] = 650 #add to

The method that came out during hash learning

learning.rb


p prices.size #Method that pulls the number of elements
p prices.keys #Method that pulls the list of keys
p prices.values #Method that pulls the list of values
p prices.has_key?(:gukbap) #A method to check if the key exists

[Conditional bifurcation]

Instructions / methods "gets" that accept input from users

learning.rb


price = gets.to_i #When converting to a number to_i
signal = gets.chomp
#gets reads one line but has a line feed code at the end
#Remove the last newline code with a method called chomp

if

learning.rb


if money > 15000
    puts "You can buy yakiniku!"
elsif money > 7000
    puts "Let's go yakiniku!"
else
    puts "I want to eat yakiniku..."
end

If it is a simple conditional branch, if can be written after it.

learning.rb


puts "You can buy yakiniku!" if money > 15000

case Processing when you want to send out some message according to the value The following can be realized with if, but in some cases it can be written neatly using case

learning.rb


case meat
when "Calvi"
  puts "Let's make the upper ribs!"
when "Loin", "Harami" #Can be separated by commas
  puts "Let's put it on!"
when "Beef tongue salt"
  puts "Only Tan won"
else
  puts "Let's definitely order tongue!"

[Repeat processing]

Use properly

--while is a condition --times is the specified number --for (each) is the number of elements

while

learning.rb


i= 0 #Initialize i with 0

while i < 10 do #Repeat less than 10
  puts "#{i}: I want to eat yakiniku"
  i += 1
end

time Useful when the number of repetitions is fixed Write the process you want to do from do to end

learning.rb


10.times do |i|
	puts "#{i}: I want to eat yakiniku"
end
#If you want to know how many loops you have, after do|variable|

If there is only one line between do and end, you can substitute {}

learning.rb


10.time { |i| puts "#{i}: hello" }

for For for some kind of collective object (array or hash) Also, only the number of elements of the object that represents the range Instructions that can repeat some processing

learning.rb


for i in 15..29 do #do is optional
  p i
end

#Array
for meat in ["tongue", "offal"] do
  p meat
end

#hash
for meat, price in {tongue:1000, offal:800} do
  p "#{meat}: #{price}"
end

each Because for uses a method called each internally for can be rewritten using each

As with the time method, if the process to be repeated is about one line It is also possible to enclose do to end in {} and express it in one line

learning.rb


(15..29).each do |i|
    p i
end

Array
 ["tongue", "offal"].each do |meat|
    p meat
end

hash
{tongue:1000, offal:800}.each do |meat, price|
    p "#{meat}: #{price}"
end

loop

learning.rb


i = 0
loop do
     p i
     i += 1
end

The process of looping forever is often used with instructions to exit the loop.

break

learning.rb


10.times do |i|
    if i == 7
        break #Exit the loop just before 7
    end
    p i
end

next

learning.rb


10.times do |i|
    if i == 7
        next #Skip 7 once
    end
    p i
end

break, next Can be used in iterative processing such as while, for, and times, including loops

[Method]

A collection of multiple processes into one

Method benefits

If you don't use the method, you need to write the same process many times. It can be written simply by grouping common processes into methods.

learning.rb


#When not using the method
puts "Good evening"
puts "I'm Prince Calvi"
puts "Good evening"
puts "I am Mr. Tan"
puts "Good evening"
puts "I am Minister Harami"

#When using the method
def introduce(name)
  puts "Hello"
  puts "I#{name}is"
end
introduce("Prince Calvi")
introduce("Mr. Tan")
introduce("Minister Harami")

Method definition

Write the process you want to put together between "def method name" and "end" This is called "defining a method" The figure on the right defines an introduce method that produces two outputs.

learning.rb


Format
def method name
processing
end

def introduce
  puts "Hello"
  puts "I'm yakiniku"
end
introduce #Call the introduce method

【argument】

Definition / call of method that receives arguments

learning.rb


Format
def method name (argument name)
processing
end
Method name (value)#Method call+Value assigned to argument

Use arguments in methods

learning.rb


def introduce(name)
  puts "Good evening"
  puts "I#{name}is" #Arguments can be used like variables in methods
end
introduce("Yakiniku brother")

Methods with arguments cannot be called without passing arguments Note that an error will occur

Receive multiple factors ・ Call

learning.rb


def meat(name, price) #From the left, the first argument and the second argument
 puts "#{name}"
 puts "#{price}Circle"
end
meat("Pork toro", 800)

【Return value】

Method with return value

You can use return in a method to receive the value at the caller By writing "return value", the method returns that value as the return value.

learning.rb


Format
def method name
return value#Returns a value to the caller (= return value)
end

def add(a,b)
  return a + b #The sum of a and b is called as the return value
end

Receive a return value

If there is a return value, the calling part of the method is replaced with the return value as it is By writing to assign the calling part of the sod to a variable You can receive the return value of the method.

learning.rb


def add(a,b)
  return a + b
end
sum = add(1,3) #Call part
puts sum #Output 4

Various return values

As for the return value, various values ​​can be used as well as the argument.

If you return a conditional expression like the one used in the if statement, You can return the boolean value (true or false) obtained as a result of the conditional expression. Methods that return a boolean value have the convention of adding a "?" To the end of the method name.

learning.rb


def meat_free?(price) 
  return price >= 10000
end

if meat_free?(14000)
	puts "Next time you visit the store, beef tongue salt service"
else
	puts "Kimchi service the next time you visit"
end

End of processing by return

return not only returns a return value, but also has the property of terminating the processing of the method. Therefore, the processing of the method after return is not executed.

learning.rb


def add(a, b)
  return a + b #The process ends here
  puts "Calculated" #Not executed
end

Multiple returns

In the method, by combining conditional branching Multiple returns can be used

learning.rb


def price_with_shipping(price)
  if price >= 10000
    return price
  end
  return price + 500
end

puts "The total amount is 3000 yen"
puts "The payment amount includes take-out meat#{price_with_shipping(8000)}It's a yen"
#Output for 8500 yen
puts "The total price of the product is 10,000 yen"
puts "Payment amount includes shipping fee#{price_with_shipping(10000)}It's a yen"
#Output for 10,000 yen

[Keyword argument]

As the number of arguments increases, it is difficult for the caller to know which argument the value goes into. By using keyword arguments, the caller can specify the arguments.

In addition to the usual method writing

  1. On the definition side, add a colon after the argument
  2. On the caller, write the argument name before the value By doing so, you can write a method with keyword arguments.

learning.rb


#How to write so far
def introduce(name, age, food)
  puts "I#{name}is"
  puts "Age is#{nage}I'm old"
 puts "What is your favorite food#{food}is"
end
introduce("Yakiniku brother", 37, "Grilled meat")
#It's hard to tell which argument each value goes into

#How to write using keyword arguments
def introduce(name:, age:, food:) #Add a colon
  puts "I#{name}is"
  puts "Age is#{nage}I'm old"
 puts "What is your favorite food#{food}is"
end
introduce(name:"Yakiniku brother", age:37, food:"Grilled meat")
#How to write the argument name when calling

【class】

--Blueprint: Class --Things: Instance

The class is like a blueprint An instance that corresponds to the actual "thing" created from the blueprint "Instance variables" that are the information that the instance has The "instance method" to call for an instance is Define in class

STEP to create an instance

STEP1 Prepare a class STEP2 Create an instance from the class STEP3 Add information to the instance

Class definition

Class can be defined by "class class name" Class names must always start with "uppercase" + "end"

learning.rb


class Menu #Class names start with a capital letter
end #Don't forget end

Instance variables

attr_accessor To have information, use "attr_accessor symbol" An instance of the Menu class can have information called name Also, this information called "name" is called an "instance variable".

learning.rb


class Menu
  attr_accessor :name
end
#An instance of the Menu class can have information called name
#This information called name is called an instance variable.

Instance generation

To create a new instance based on the class (blueprint) "class name.new" Also, the instance created by "variable name = class name.new" can be assigned to the variable.

Assign a value to an instance variable

To give information to the instance, prepare it in the class You need to assign a value to an instance variable Specifically, by setting "instance.variable name = value" You can set a value for that instance variable

learning.rb


class Menu
  attr_accessor :name
  attr_accessor :price
end
menu1 = Menu.new
menu1.name = "Chateaubriand" #Chateaubriandを代入
puts menu1.name #Output Chateaubriand

[Instance method]

Define / call a method in a class

The method defined in the class is called as used for the instance. Specifically, by doing something like "instance.method name" That method can be called = instance method

learning.rb


class Menu
  attr_accessor :name
  attr_accessor :price
  def show
    puts "I'm meat"
  end
end
menu1 = Menu.new
menu1.show #instance.Call by method name

Instance methods can also take arguments and return a return value

learning.rb


class Menu
	|
  def show(data) #argument
    return "I#{data}is" #Return value
  end
end
menu1 = Menu.new
puts menu1.show("Meat")

Handle instance variables in instance methods

By using "self" in the instance method and setting it as "self.variable name" Can handle instance variables In the instance method, the variable "self" The called instance itself is assigned

learning.rb


class Menu
  |
 def show_name
  puts "I#{self.name}is"
 end
end
menu1 = Menu.new
menu1.name =Garlic
menu1.show_name #Instance method call

initialize method

You can execute the process immediately after creating the instance. Called automatically immediately after creating an instance with "class name.new"

The initialize method can be defined like any other instance method The following is immediately after the Menu instance is created by "Menu.new" The initialize method is called and the processing in it is being executed

learning.rb


class Menu
	|
  def initialize
    puts "Menu generated"
  end
	|
end
menu1 = Menu.new
# Menu.The initialize method is automatically called when new is executed

Handle instance variables with initialize method

Because you can handle instance variables with "self.variable name" in the instance method You can assign a value to an instance variable with "self. variable name = value"

learning.rb


class Menu
    |
  def initialize
    self.name = "Marucho"
  end
    |
end
menu1 = Menu.new
puts menu1.name
#Immediately after instantiation"Marucho"To the instance variable name

Arguments of initialize method

The initialize method can pass arguments like a normal instance method At that time, by passing an argument to "class.new" You can pass that value to the initialize method

learning.rb


class Menu
    |
  def initialize(message) #The meat is turned inside out only once, but it comes over
    puts message
  end
    |
end
menu1 = Menu.new("Meat is turned inside out only once")

Assign a value to an instance variable with the initialize method

By assigning the argument value to the instance variable with the initialize method You can change the value of the instance variable for each instance At that time, you can write it easily by using keyword arguments

learning.rb


class Menu
	|
  def initialize(name:, price:)
    self.name = name
	self.price = price
  end
   |
end
menu1 = Menu.new(name: "Marucho", price: 800)

[File division]

(Example at the time of division) After moving the definition of Menu class from index.rb to menu.rb Make the code in menu.rb available in index.rb By saying "require" ./menu "" in the top line of index.rb You will be able to read the code in menu.rb

learning.rb


# index.rb
require "./menu"
menu1 = Menu.new(name: "hearts",・ ・ ・)
  |

Instance created from Menu class can also be an element of array Assign an array with each instance as an element to the variable menus The following is a case where each menu is displayed by using the each statement for the array.

learning.rb


# index.rb
menu1 = Menu.new(name: "hearts", price: 900)
menu2 = Menu.new(name: "lever", price: 800)
  |
menus = [menu1, menu2,  ....]
menus.each do |menu| #Display menus one by one using each statement
  puts menu.info
end

[Inheritance]

Creating a new class based on a certain class is called "inheritance". By setting "class new class name <original class name" You can define a new class by inheriting another class The new class is "child class" The original class is the "parent class"

learning.rb


require "./menu"
class Food < Menu
end

Instance of child class

The child class inherits the instance variables and instance methods of the parent class An instance of the Food class is as shown in the example below. You can call instance variables and instance methods of Menu class

learning.rb


# index.rb
food1 = Food.new(name: "Akasen", price: 900)
puts food1.name
puts food1.info

# menu.rb
class Menu
  attr_accessor :name
   |
  def info
    return "#{self.name} #{self.price}Circle"
  end
end

Add an instance variable to a child class

Use "attr_accessor" as usual to add an instance variable to a child class The Food class below inherits from the Menu class ・ Name ・ price ・ calorie 3 instance variables can be used

learning.rb


# index.rb
food1 = Food.new(name: "Akasen", price: 900)
puts food1.name
puts food1.info

# menu.rb
class Menu
  attr_accessor :name
  attr_accessor :price
   |
end

# food.rb
class Food < Menu
  attr_accessor :calorie #Added "calorie" to Food class
end

override

If you define a method with the same name as the method in the parent class in the child class Method can be overridden = "override" When overridden, the child class instance is not a parent class method Call the method defined in the child class

** (Override mechanism) ** An instance of a child class preferentially calls a method defined in the child class. Therefore, if the child and parent classes have methods with the same name Since the method of the child class is called, the content of the method will be overwritten as a result.

super By setting "super" in the overridden method, You can call a method with the same name in the parent class Since we are calling the method to the last Arguments need to be passed to super according to the method definition of the parent class

learning.rb


# menu.rb
class Menu
  attr_accessor :name
  attr_accessor :price
  def initialize(name:, price:)
    self.name = name
	self.price = price
  end
   |
end

# food.rb
class Food < Menu
  attr_accessor :calorie
  def initialize(name:, price:, calorie:)
    super(name: name, price: price) #Call the method of the same name in the parent class
	self.calorie = calorie
  end
   |
end

[Data class]

Date class = Class that handles dates Date class is a class already prepared by Ruby By loading with require, you can use it without having to define the class yourself.

(Note that the required classes are slightly different for the already prepared classes.)

learning.rb


require "date" 
#  "./date"Note that it is not

Instance of Date class

The Date class is the same as the classes we have dealt with so far You can create an instance by setting Date.new When you puts an instance of the Date class You can display the date as below

learning.rb


reequire "date"
date1 = Date.new(2020,12,18) #Create a Date instance by passing "date" as an argument
puts date1
#Output 2014-07-31

Get a Date instance for today's date

In the Date class, by setting Date.today, You can create an instance of today's date

learning.rb


require "date"
date1 = Date.today
puts date1

[Class method]

Class method can be defined by "def class name.method name" The difference from the instance method is that the class name must be written before the method name.

The following defines a class method called "is_discount_day?" In the Menu class.

Class methods are just as defined It can be called by setting "class name.method name"

learning.rb


Definition
def class name.Method name
  #processing
end

Example
class Menu
  |
  def Menu.is_discount_day?
    #processing
  end
end
puts Menu.is_discount_day?

Review of instance methods and class methods

The method to call for the instance is "instance method" The method to call for the class is "class method"

learning.rb


class Menu
  |
  def info #Instance method definition
  end
end
menu1 = Menu.new
menu1.info #Instance method calls to instance

learning.rb


class Menu
 def Menu.is_discount_day? #Class method definition
 end
end
Menu.is_discount_day? #Class methods call on the class

Recommended Posts

Introduction to Ruby basic grammar with yakiniku
Introduction to Ruby 2
[Ruby] Introduction to Ruby Error statement
Review of Ruby basic grammar
I tried to summarize the basic grammar of Ruby briefly
Introduction to Ruby processing system self-made
Introduction to algorithms with java-Shakutori method
Memorandum (Ruby: Basic grammar: Iterative processing)
Introduction to Ruby (from other languages)
With ruby ● × Game and Othello (basic review)
Introduction to algorithms with java --Search (depth-first search)
Memorandum (Ruby: Basic Grammar: Classes and Instances)
Convert JSON to TSV and TSV to JSON with Ruby
Introduction to algorithms with java --Search (breadth-first search)
Get started with "Introduction to Practical Rust Programming" (Day 4) Call Rust from Ruby
Start with a browser Ruby game programming: Introduction to Nyle-canvas (DXRuby style)
Sample to create PDF from Excel with Ruby
Introduction to Robot Battle with Robocode (Environment Construction)
[Ruby] Basic key to be strong in refactoring
Java engineers now compare to learn the basic grammar of Ruby Part 1 (Basic, Variables)
Ruby basic terms
[Docker] Introduction to docker compose Basic summary of docker-compose.yml
Introduction to algorithms with java --Search (bit full search)
Introduction to algorithms with java-Search (Full search, Binary search)
Ruby Learning # 1 Introduction
Java basic grammar
Java basic grammar
Introduction to SWING
Try to link Ruby and Java with Dapr
[Monthly 2017/04] Introduction to groovy !! ~ Java grammar / specification comparison ~
Introduction to web3j
Introduction to Micronaut 1 ~ Introduction ~
Java basic grammar
[Java] Introduction to Java
Introduction to migration
Try to get redmine API key with ruby
Java basic grammar
How to write test code with Basic authentication
AtCoder ABC127 D hash to solve with Ruby 2.7.1
Introduction to java
Introduction to Doma
Introduction to Robot Battle with Robocode (Beginner Development)
[Introduction to Spring Boot] Authentication function with Spring Security
Java engineers now compare to learn the basic grammar of Ruby Part 2 (classes, methods)
[Ruby] Basic code list. Keep the basics with examples
[Introduction] Try to create a Ruby on Rails application
[Introduction to Docker x ECS] ECS deployment with docker compose up
How to make LINE messaging function made with Ruby
Converting TSV files to CSV files (with BOM) in Ruby
Memorandum (Ruby: Basic grammar: Use by naming the process)
Get started with "Introduction to Practical Rust Programming" (Day 3)
Introduction to Java for beginners Basic knowledge of Java language ①
Feel the basic type and reference type easily with ruby 2
Introduction to RSpec 4. Create test data with Factory Bot
About Android basic grammar
Install Ruby 3.0.0 with asdf
Introduction to JAR files
Introduction to Ratpack (8)-Session
Ruby learning points (basic)
Introduction to RSpec 1. Test, RSpec
Introduction to bit operation