[RAILS] What you can do with ruby ​​Quick reference teaching materials (for beginners)

Preface

The basic grammar and the behavior of the objects in each class are summarized without any extra explanation so that they can be used for review. We hope that you can jump to the item you want to look back from the table of contents and use it for review. It is written so that it can be read if you have enough knowledge to understand the difference between character strings and numerical values ​​and the specifications of variables.

table of contents

Basics

--puts and p methods -Method -Method Basics -Argument type -Block Arguments -Return value -Authenticity and calculation -True / False -Conditional branch -Relational Calculus -Logical operation

object -Numeric (Integer, Float) -Numeric description method -Numerical calculation -Frequently used methods of numeric type -String -Character string description method -String operation -String type frequently used method -Regular expression (Regexp) -Regular expression description method -Frequently used regular expression summary -Symbol -Symbol description method -Array -Array description method and data acquisition -Array Manipulation -Frequently used methods of array type -Hash -Hash description method and data acquisition -Hash Manipulation -Repeat method

Basics

puts and p methods

--puts come out with the object processed to make it easier to see --The contents of the array are broken out one by one. -Escape characters such as \ n are displayed after the escape characters are converted. --p displays the object as it is --The array is displayed as it is in the form of [] --Escape characters are displayed as they are

** Example **

test.rb


a = [1,2,3]
s = "The first line\n2 line"
puts "~~ In the case of puts ~~"
puts a
puts s

puts "~~ In case of p ~~"
p a
p s

Execution result


~~ In the case of puts ~~
1
2
3
The first line
2nd line
~~ In case of p ~~
[1, 2, 3]
"The first line\n2 line"

Method

A method is a processing set that summarizes processing.

Method basics

--After defining, you can call it by writing the method name (1) --You can pass data to the method by using arguments (2) --Arguments can be used as variables in methods -Multiple arguments can be specified by separating with, --There are some existing methods in ruby ​​(3) --You can also specify the target and call it (3) --A thing that changes the contents of the target is called a ** destructive method ** (3) --Many of the methods provided by ruby ​​are destructive if you add a! After them. --You need to understand class and receiver for targeting --The method always returns a return value. (The return value will be described later)

** Description method **

# 1.Method definition
def method name(Argument name, Argument name2)
end

# 2.Method call
Method name(Argument name)

** Example **

test.rb


# 1.Method definition
def greeting(name, name2)
  puts "Hello"
  puts name
  puts name2
end

# 2.Method call
puts "~~ Execution result 1 ~~"
greeting("Tanjiro", "Nezuko")

# 3.Existing method to specify the target
a = 1.to_s #to_s converts the target to a string
puts "~~ Execution result 2 ~~"
p a

# 4.Destructive and non-destructive methods
text1 = "abc"
text2 = "def"

#upcase is a method to capitalize the target
text1.upcase #Return value"ABC"Just return, the contents do not change(The return value will be described later.)
text2.upcase! #Capitalize the contents

puts "~~ Execution result 3 ~~"
puts text1
puts text2

Execution result


~~ Execution result 1 ~~
Hello
Tanjiro
Nezuko
~~ Execution result 2 ~~
"1"
~~ Execution result 3 ~~
abc
DEF

Argument type

The arguments below are referred to as arg.

--Takes an * arg array as an argument. (1) --Receives a ** arg hash as an argument. (1) --arg = default value Set the default value for the argument. If not specified at the time of the call, the default value will be set) --arg: default value Set the argument with the keyword. (2) --The & block block is received as it is. The explanation is omitted here.

** Example (When using two or more types of arguments at the same time, there may be a recommended order, but this time I will omit it) **

test.rb


#Take an array and hash as arguments
def test1(*arg1, **arg2)
  p arg1
  p arg2
end

puts "~~ Execution result 1 ~~"
test1([1, 2],{a: 'a', b: 'b'})

#Specify arguments using keyword arguments
def test2(arg1: "default", arg2: "defalult")
  p arg1
  p arg2
end


puts "~~ Execution result 2 ~~"
test2(arg2: "doraemon")

Execution result


~~ Execution result 1 ~~
[[1, 2]]
{:a=>"a", :b=>"b"}
~~ Execution result 2 ~~
"default"
"doraemon"

Block argument

Arguments used in loop processing etc., this time we will explain on the premise of the method that performs loop processing. Below, the block argument is referred to as block.

** Description method **

# 1.How to pass blocks
object.Method{ |block| }
Or
object.Method do|block|
end

** Example **

test.rb


array = [1, 2, 3]
count = 1

# 2.Block movement in loop processing
array.each do |number| #Each executes loop processing only for the contents of the target array and data such as hash.
  puts "#{count}Second data"
  puts number
  count += 1 #Increase count by 1
end

Execution result


1st data
1
Second data
2
Third data
3

Return value

The return value is the value that is finally returned when processing a method, if statement, etc.

--The return value in ruby ​​is basically the last line of the process. --In the case of method, before end --In the case of if statement, before end or the next elsif --Return values ​​may be returned during processing such as logical operations. (See below) --You can specify the return value by describing return. If return returns a return value, the process ends at that stage.

** Example **

test.rb


def test_method(arg)
  1
  arg = arg + 3
  arg #This is the last line
end

a = test_method(4)
puts a

Execution result


7

Authenticity and calculation

Authenticity

--Every object has a truth. --The truth is either true or false. --All things that become true are false (FalseClass object), except nil. --There are two things that become false: false (FalseClass object) and nil. -If you attach! To an object, the truth will be reversed. -Add !! to indicate the original truth.

1 #=> true
"abc" #=> true
true #=> true

nil #=> false
false #=> false

!1 #=> false
!! 1#=> true

** Example **

test.rb


puts !!1

Execution result


true

Conditional branch

--Conditional branching is possible. --If the truth of the expression is true, the processing up to if ~ end (or the next elsif or else) is executed. (1) --In elsif, you can write the processing when another expression is true, and in else, the processing when all the expressions are false. (1) --The last line of the if statement is the return value. (2)

** Description method **

if expression
processing
elsif expression
processing
else
processing
end

** Example **

test.rb


# 1.Conditional branch
puts "~~ Execution result 1 ~~"
if true #=>The truth of true is true
  puts "true"
else
  puts "false"
end

puts "~~ Execution result 2 ~~"
if false #=>The truth of false is false
  puts "1"
elsif "ab" #=>The truth of the string is true
  puts "2"
else
  puts "3"
end

# 2.Return value
puts "~~ Execution result 3 ~~"
a = 
  if false #The truth of false is false
    "Various processing"
    'Return value 1' #This is the last line of if
  else
    "Various processing"
    'Return value 2' #This is the final length of else
  end
puts a

Execution result


~~ Execution result 1 ~~
true
~~ Execution result 2 ~~
2
~~ Execution result 3 ~~
Return value 2

Other conditional branching

Detailed explanation is omitted here.

--If false of unless if, the version to be executed --Statement that branches the condition by the result of the case expression: ** Reference article ** --A statement that processes the ternary operator true and false at once: ** Reference article **

Relational calculus

It is an expression that returns the truth depending on the left and right comparison result The following relational operators

--</ (>) true if the right side (/ left side) is larger than the left side (/ right side) --<=/(> =) true if the right side (/ left side) is greater than or equal to the left side (/ right side) --==/(! =) True if the left and right sides are equal (/ not equal)

** Example **

test.rb


if 1 < 2 #=>this(1 < 2)Expression itself is treated as a true object
  puts "true"
else
  puts "false"
end

Execution result


true

Logical operation

It is an expression that returns ** return value ** depending on the truth of the left and right

--Logical operator (1) --&& If both the right side and the left side are ture, the true ** value is returned **

** Example **

test.rb



# 1.Logical operation
puts "~~ Execution result 1 ~~"
if true && false #false because neither true nor false is true
  puts "true"
else
  puts "false"
end

puts "~~ Execution result 2 ~~"
if true || true && false #True first&&Calculate false
  puts "true"
else
  puts "false"
end

# 2.Return value of logical operation
puts "~~ Execution result 3 ~~"
a = "ab" && nil && false
p a

puts "~~ Execution result 4 ~~"
b = nil || "a" && false || "c"
p b

Execution result


~~ Execution result 1 ~~
false
~~ Execution result 2 ~~
true
~~ Execution result 3 ~~
nil
~~ Execution result 4 ~~
"c"

** Supplement **

--Execution result 3 --1 1. "ab" && nil is calculated, and the nil of the result false or false is the return value. ―― 2. Calculate nil && false, both are false, so nil on the left side is the return value ―― 3. Result nil is substituted --Execution result 4 ―― 1. Calculate "a" && false first, and the return value is false, which is false or false.

About the priority of calculation

--Processing will be performed in descending order of priority. : Reference site -By adding (), you can give priority to the inside of that ().

class

class basics

If you don't know about class, please study Refer to here because this Advent_Calendar article is easy to understand.

--You can create an instance of the class with the new method (2) --All classes belong to a class called Class --new method belongs to Class, so it can be used for any class --Methods defined in a class can only be called from an instance of that class (3) --Class methods can only be called from class objects (4)

** Description method **

# 1.definition of class
class class name
  #Creating a class method
  def self.Class method name
  end
end

# 2.Create an instance of class
class_object =Class name.new()

# 3.Calling an object that belongs to class
class_object.Method

# 4.Calling a class method
Class name.Class method name

Inheritance and override

--The inheritance class inherits the functions of other classes (1) --At this time, the inherited class is called superClass, and the inherited class is called subClass. --Override Override the superClass method (2) --Can be done by defining a method with the same name as the superClass method in subClass --super Description to call the method before overriding (3)

** Description method **

class The class name to take over<Class name to be inherited
end

** Example **

test.rb


class TestSuper
  def test_method
    'Can be inherited'
  end

  def hello
    puts "Hello"
  end
end
class TestClass < TestSuper
# 2.Rewrite superClass method
  def hello
    super # 3.Call the hello method defined in superClass(puts "Hello")
    puts "World"
  end
end


class_object = TestClass.new

puts "~~ Execution result 1 ~~"
# 1.Call the method inherited from superClass
puts class_object.test_method

puts "~~ Execution result 2 ~~"
# 2.Call the overridden method
puts class_object.hello

Execution example



~~ Execution result 1 ~~
Can be inherited
~~ Execution result 2 ~~
Hello
World

object

Numeric type

--The main class is Numeric --Integer is an Integer class that inherits Numeric --Float class that inherits Numeric for decimals --When dealing with numbers normally, it becomes an Integer class

How to write numbers

--Generation of numerical values --If you write numbers directly, it becomes a number type. --Integer if there is no decimal point --Float if you write after the decimal point --0b 0`` 0x If you put it at the beginning, it will be 2, 8 and hexadecimal respectively.

** Description method **

10 #=> Integer
10.5 #=> Float

0b1010 #=>Integer, binary 1011(11 in decimal)

Numerical calculation

--Four arithmetic operations --+ -`` * Addition, subtraction, and multiplication symbols (1), respectively. --/ Divide, round down to the nearest whole number for Integer (2) --In the case of % Integer, calculate the remainder of the division (3) --Bitwise operation --& | ^ Symbols of and, or, xor, respectively --<< >> Left shift and right shift, respectively --~ Invert the bits on the right side --When calculating with Integer and Float, integer type is changed to Float --Be careful of errors when dealing with float types: Reference article on errors

** Example **

test.rb


# 1.Addition / subtraction, multiplication
1 + 1 #=> 2
3 - 1 #=> 2
2 - 5 #=> -3
2 * 2 #=> 4

# 2.division
5 / 3 #=> 1
5 / 3.0 #=> 1.666666....7 #Error occurs

# 3.Ask for the remainder
5 % 3 #=> 2

Frequently used methods of numeric type

--. To_s (arg) Conversion to string --If you specify an argument, it will be converted to that radix. --. Even? .odd? Returns true if even or odd, respectively (Integer only) --. Divmod (arg) Returns the quotient and remainder as an array --Return the result of dividing the target by the argument by [quotient, remainder]

String type

--String class --General types when dealing with text

How to write a character string

--How to generate a character string (1) --Represent by enclosing in " "'' (single quotation marks) or "" (double quotation marks) -The difference between'' and "" is whether expression expansion and escape characters are applied (3) -- Here document`` << TEXT << Identifier Expressed by enclosing it in an identifier --By describing expression expansion`` # {} # {variable} in the character string, the value assigned to the variable in {} is output as a character string (2) --Frequently used escape characters and explanations: Reference article --% notation, Stirng.new will not be explained

** Example (the blue part is the character string) **

python


# 1.String generation
"stirng"
<<TEXT
Here document
Even if you break a line
Easy to see! !!
TEXT

# 2.Expression expansion
element = "water"
"#{element}Breathing" #=> "水Breathing"

# 3. ''Cannot expand expressions or convert escape characters
'#{element}Breathing' #=> '#{element}Breathing'
'The first line\n2 line\line n3\n' #=> 'The first line\n2 line\line n3\n'

String manipulation

--Concatenation`` + You can combine strings with + (1) --Can be repeated using * * numbers (2) --Use [] [] and << to treat it like an array of characters (3) --String == Note that this is not an array of characters (4)

** Example **

# 1.String concatenation
element = "fire"
element + "Breathing" #=> "火Breathing"

# 2.Repeat string
"I'm hungry" * 3 #=> "I'm hungryI'm hungryI'm hungry"

# 3.Specify the number of characters like an array
text = "abcdef"

text[0] #=> "a"

text << "g"
text #=> "abcdefg"

# 4.important point
text[0].upcase! #In this case the return value is"A"But text is"Abcdefg"do not become

Frequently used methods of string type

Destructive explanation here For a description of regular expressions here

--. To_i`` .to_f Conversion to numbers --Convert the target to Integer and Float types, respectively. --upcase`` downcase Conversion to uppercase and lowercase (**! Is destructive ) --. Gsub (arg1, arg2) Character replacement and adjustment (! Is destructive ) --Convert the target character string that applies to the first argument to the second argument --Regular expressions can be used as arguments --. Delete (* arg) Partial deletion (! Is destructive **) --Delete the character specified in the argument --Regular expressions can be used as arguments

Regular expression

--Class is Regexp --Objects that handle regular expressions --Used as an argument of string manipulation method --Regular expression description: Reference article

How to write a regular expression

--Description between // --When replacing, enter the character to be replaced between "" --\ number At that time, use \ to specify the number.

** Example **

python


#Use regular expression as argument of gsub method
 "I'm studying Ruby".gsub(/\w+/, "programming")
#=> "I am studying programming"

Summary of frequently used regular expressions

--Multiple conditions --[abc] a or b or c

--Specify quantity --{n, m} n or more and m or less, if there is one in {}, that number --+/+? 1 or more characters * If there is no problem with the pattern, fetch as long/short characters as possible --* /*?0 characters or more * If there is no problem with the pattern, fetch as long/short characters as possible --? You don't have to

symbol

--The class is Symbol --Objects that handle characters --Better read speed and memory efficiency than strings --Often used for hash keys --The reference destination of the same symbol is always the same: Reference article about reference --Therefore, it is not omitted as the content of the text (the reason is omitted) --Can be converted to a character string with the to_s method

How to write a symbol

--Generate a symbol with: in front of the character --Numbers and symbols cannot be at the beginning -Can be used when enclosed in "", and expression expansion is also possible -: A and:'a' are treated as the same symbol ** Description method **

#Generate symbol
:symbol
a = "abc"
:#{a} #=> :"abc"

Array

--The class is Array --Object that handles multiple data at once

Array description method and data acquisition

--Generation of array --Enclose with [,] [] and separate each data with, (1) --Generate with Array.new (number of elements) {default value} (2) --array [n] By writing [number] next to the array, you can get the data stored in that location (3) --Numbers start from 0 --Variables can be used as long as the content is Integer type, and Renge type can also be used (4) --It is also possible to generate an array of multidimensional array array (5) --array [n] [m] When retrieving data, specify the numbers in order from the outside.

** Description method **

# 1~2.Array generation
[1, 2, 3]
Array.new(3){ "default" } #=> ["default", "default", "default"]

# 3.Data acquisition 1
array = [1, 2, 3, 4]
array[0] #=>1 * Array starts from 0
array[2] + 7 #=>10 * Contents data is treated as the original data type

# 4.Data acquisition part 2
array = [1, 2, 3, 4]
array[array[1]] #=> 3 ※array[1]The contents are 2, array[2(array[1]Contents)]Contentsは3
array[1..2] #=> [2, 3] ※1..2 is a range object between 1 and 2(Renge)

# 5.Multidimensional array
#Array generation
[["a", "b", "c"], ["e", "f", "g"]]
#Data acquisition
array = [["a", "b", "c"], ["e", "f", "g"]]
array[0][1] #=> "f"

Array manipulation

--Update contents You can update the value by specifying the number and assigning it. --Addition of contents --<< Value Data can be added to the end of the array (1) --If you add data to a number that does not exist, the array will be expanded, and nil will be inserted between the expanded ranges (2) --Concatenation of arrays, set (3) --+ Concatenation + can be used to generate an array by concatenating arrays.

** Example **

array = [1, 2, 3]

# 1~2.Add data to the array
array << 4 #=> array == [1, 2, 3, 4]
array[7] = 8 #=> array == [1, 2, 3, 4, nil, nil, nil, 8]

# 3.Concatenation and set of arrays
a1 = [1, 2, 3, 4]
a2 = [3, 4, 5, 6]

a1 + a2 #=> [1, 2, 3, 4, 3, 4, 5, 6]
a1 | a2 #=> [1, 2, 3, 4, 5, 6]
a1 - a2 #=> [1, 2]
a1 & a2 #=> [3, 4]

Frequently used methods of array type

--. Join (arg) Returns a string that concatenates the contents of an array --If you pass a character as an argument, that character becomes the delimiter. --. Last Get the last element of the array --For other iterative processing, click here (#繰り返しメソッド)

hash

--Class is Hash --Almost the same object as params of rails --Can also be used as a keyword argument

Hash description method and data acquisition

--Hash generation (1) --Enclose in {key => value} {} and describe the set of key and value separated by ,. --Use some object for key --How to write key and value (1) --key => value Basic writing --How to write when using symbols for key: value key -Synonymous with: key => value -If you write "key": value, key is recognized as a symbol (2) --You can get the value by specifying the key of hash [key] hash (3) --If you specify a key that does not exist, nil is returned (it does not become an error) (3) --Hash can be stored in hash (4) --hash [: p_key1] [: key1] You can get the value by specifying the key from the outside.

** Example **

# 1.Hash generation
{"key1" => "value1", "key2" => "value2"} #Normal writing
{key1: "value1", key2: "value2"} #Abbreviated writing when using symbols

# 2.Precautions for abbreviated writing
{"key1": "value1"} #=> {:key1 => "value1"} "key":Becomes a symbol

# 3.Get value
hash = {main_character: "Tanjiro", hiroine: "Nezuko"}
hash[:main_character] #=> "Tanjiro"
hash[:oni] #=> nil

# 4.Hash that stores the hash
hash = {kimetu: {main_character: "Tanjiro", hiroine: "Nezuko"}}
hash[:kimetu][:hiroine] #=> "Nezuko"

Hash manipulation

--The value can be updated by specifying the hash key and assigning it. --If the specified key does not exist, it will be added.

** Example **

hash = {main_character: "Tanjiro", hiroine: "Nezuko"}
hash[:hiroine] = "Inosuke" #=> hash == {main_character: "Tanjiro", hiroine: "Inosuke"}
hash[:oni] = "Nezuko" #=> hash == {main_character: "Tanjiro", hiroine: "Inosuke", oni: "Nezuko"}

Repeat method

--Method for loop processing --Methods of Enumerable class inherited by Array class and Hash class --Therefore, it can be handled as an array or hash

Frequently used methods

--Perform loop processing for the number of target values

Recommended Posts

What you can do with ruby ​​Quick reference teaching materials (for beginners)
Learn Java with "So What" [For beginners]
What to do if you should have installed Rails but an error occurs with rails -v (for beginners)
You can do it with copy! Aspect-oriented programming (Android)
I tried to explain what you can do in a popular language for web development from a beginner's point of view.
Scraping for beginners (Ruby)
What to do if you installed Ruby with rbenv but the version does not change
What to do when you launch an application with rails
In Ruby you can define a method with any name
[Ruby comprehension check] Can you explain what is happening? && and and
[Ruby] What is `!!` used for?
[For beginners] You will definitely understand in 10 minutes! What is JavaBeans?
[For beginners] Ruby is said to be ruby, but what about it?
What to do if you get angry with OpenSSL with pyenv install
[Rails] What to do if you can't get parameters with form_with
Automatic file upload with old Ruby gem What to do with Watir