[Ruby] List of basic commands

[Ruby] List of basic commands

A list and examples of basic Ruby commands.

table of contents

  1. [Differences between puts, print and p](Differences between # puts-print-p)
  2. Constant
  3. [Object class list display (.class)](#Object class list display class)
  4. [Object method list display (.methods)](#Object method list display methods)
  5. [Calculation after decimal point](#Calculation after decimal point)
  6. [Specify the number of decimal point display digits](#Specify the number of decimal point display digits)
  7. [format (or sprintf)](#format or -sprintf)
  8. [round, ceil, floor method](# round-ceil-floor method)
  9. String
  10. [Expression expansion](# expression expansion)
  11. Concatenate
  12. [Repeat](#Repeat string)
  13. [Character count (.length)](#Character count length)
  14. [Convert from string to number (.to_i)](#Convert from string to number to_i)
  15. [Array](# array)
  16. [Get array elements](#Get array elements)
  17. [Add element (push or <<)](#Add element push-or-)
  18. [Get array length (size, length, count)](# Get array length size-length-count)
  19. Sort
  20. [Hash Object](#Hash Object)
  21. Create and Call (#Create and Call)
  22. [Add Element](#Add Element)
  23. [Delete element (.delete (: key name))](# Delete element delete key name)
  24. [Conditional branch](# Conditional branch) 13. if 14. case,when
  25. Repeat 14. for in 15. each do 16. while 17. times do 18. loop + break
  26. [skip (if next)](# skip if-next)
  27. Create and Call Method (#Create and Call Method)
  28. Create Class and Instantiate (#Create Class and Instantiate)

## Difference between puts, print, p There are subtle differences between them, but you only have to remember p for puts.

The difference between them is the presence or absence of line breaks and the presence or absence of type representation.

Method puts p print
Use For production For debugging Remnants of python?
new line Yes Yes None
Type representation None Yes None

Difference between puts and print (with or without line breaks)


puts "Hello"
puts 123

#Hello
#123


print "Hello"
print 123

#Hello 123

▼ In case of "p", double quotation marks are added to the text of the character string.

Difference between puts and p (with or without type representation)


puts "Hello"
puts 123

#Hello
#123


p "Hello"
p 123

#"Hello"
#123

## constant -Define variables in uppercase ・ Use Ansco to connect multiple words -An error occurs when overwriting or redefining
TAX_RATE = 1.0
puts TAX_RATE

#Overwrite instruction
TAX_RATE = 1.5

#warning: already initialized constant TAX_RATE
#warning: previous definition of TAX_RATE was here

## Object class list display (.class) `p object.class`
p 1.1.class

#Float

## Display method list of object (.methods) `p object.methods`
p 1.1.methods

#[:-@, :**, :<=>, :<=, :>=, :==, :===, :eql?, :%, :inspect, :*, :+, :-, :/, :<, :>, :to_int, :coerce, :to_s, :divmod, :to_i, :to_f, :to_r, :fdiv, :modulo, :abs, :magnitude, :zero?, :finite?, :infinite?, :floor, :ceil, :round, :truncate, :positive?, :negative?, :numerator, :denominator, :rationalize, :arg,Omitted below...
p "abc".methods

#[:encode, :encode!, :unpack, :unpack1, :include?, :%, :*, :+, :count, :partition, :to_c, :sum, :next, :casecmp, :casecmp?, :insert, :bytesize, :match, :match?, :succ!, :<=>, :next!, :upto,Omitted below...

## Calculation after the decimal point If ".0" is added to the integer to be calculated, the decimal point is displayed. ┗ Either one ┗ Does not specify the number of digits ┗ Truncate if not
p 8.0 / 3
p 8/3.0
p 8/3

#2.6666666666666665
#2.6666666666666665
#2

## round, ceil, floor methods `.round`: Rounding `.ceil`: Round up `.floor`: Truncate
p 8.0/7
p (8.0/7).round
p (8.0/7).ceil
p (8.0/7).floor

#1.1428571428571428
#1   round
#2   ceil
#1   floor

## Specify the number of decimal point display digits ### format (or sprintf) `format ("%. Number of digits f ", target number)`
calc = 8/3.0

puts format("%.2f", calc)
puts sprintf("%.2f", calc)

#2.67
#2.67

round, ceil, floor methods

Object.round (number of digits) Object.ceil (number of digits) Object .floor (number of digits)

puts calc.round(2)
puts calc.round(3)

#2.67
#2.667


puts calc.ceil(2)
puts calc.ceil(3)

#2.67
#2.667


puts calc.floor(2)
puts calc.floor(3)

#2.66
#2.666

## String

Expression expansion

puts" # {formulas and variables} " ┗ Double quotation ┗ Output as it is if it is single

puts "tax #{1000 * 0.10}"
#tax 100.0

puts 'tax #{1000 * 0.10}'
#tax #{1000 * 0.10}

### Linking `puts string + string`
puts "Hello" + "World"

#HelloWorld

### Repeat string `puts string * n`
puts "Hello★" * 5

#Hello★Hello★Hello★Hello★Hello★

### Character count (.length) `puts string.length`
str = "hello world"
p str.length

#11

### Convert from string to number (.to_i) `puts string.to_i`
str = "123"

p str
p str.to_i

#"123"
#123

## Array ### Get elements of an array `Variable = [,,,]`
colors = ["red", "blue", "white"]

p colors[0]
p colors[3] #nil
p colors

#"red"
#nil
#["red", "blue", "white"]

### Add element (push or <<) · `Object.push (additional element)` · `Object << (additional element)`
colors = ["red", "blue", "white"]

p colors.push("green")
#["red", "blue", "white", "green"]

p colors << ("black")
#["red", "blue", "white", "green", "black"]

### Get array length (size, length, count) -`Object.size` · `Object .length` · `Object.count`
colors = ["red", "blue", "white", "green", "black"]

p colors.length
p colors.size
p colors.count

#5
#5
#5

### sort ・ `Object.sort` · `Object.sort.reverse`
colors = ["red", "blue", "white", "green", "black"]

p colors.sort
p colors.sort.reverse

#["black", "blue", "green", "red", "white"]
#["white", "red", "green", "blue", "black"]
numbers = [5, 8, 1, 4, 9]

p numbers.sort
p numbers.sort.reverse

#[1, 4, 5, 8, 9]
#[9, 8, 5, 4, 1]

## Hash object ### Create and call There are three ways to write it, but you only have to remember the abbreviation.

** Create ** Variable = {key: value, key: value ,,,}

call Variable [: key name]

scores = {tanaka:100, sato:80, ito:50}

p scores
p scores[:sato]

#{:tanaka=>100, :sato=>80, :ito=>50}
#80

▼ Other description method

All the same below


score1 = {"tanaka" => 100, "sato"=>80, "ito"=>50 }
score2 = {:tanaka =>100, :sato=>80, :ito=>50}
score3 = {tanaka:100, sato:80, ito:50}

p score1
p score2
p score3

#{:tanaka=>100, :sato=>80, :ito=>50}
#{:tanaka=>100, :sato=>80, :ito=>50}
#{:tanaka=>100, :sato=>80, :ito=>50}

### Add element `Variable [: key name] = value`
scores = {tanaka:100, sato:80, ito:50}

scores[:suzuki] = 40
p scores
 
#{:tanaka=>100, :sato=>80, :ito=>50, :suzuki=>40}

### Delete element (.delete (: key name)) `Variable.delete (: key name)`
scores = {tanaka:100, sato:80, ito:50, suzuki:40}

scores.delete(:suzuki)
p scores
 
#{:tanaka=>100, :sato=>80, :ito=>50}

## Conditional branch

if Branch the process with ** conditional expression **. if, elsif, else, end

python


stock = 5  #stock

if i >= 10
    puts 'Stock: ◎'
elsif i > 3
    puts 'Inventory: △'
elsif i == 1
    puts 'Stock: Last 1'
else 
    puts 'Stock: ×'
end

#Inventory: △

case,when Branch the conditional expression by ** value **. `case, when, else, end`

Case syntax structure


#case Variable you want to evaluate
#when number
#processing
#when range (starting value)..closing price)
#processing
#when range (starting value)..closing price)
#processing
#     else
#processing
# end

** ▼ Example **

python


age = 6

case age 
    when 0..5
        puts 800
    when 6..11
        puts 1800
    else 
        puts 2500
end 

#1800

Start price .. Close price ┗ Range from start price to close price


## repetition for in `for variable in range`

Array


x = ["A", 1, "b", 3]

for i in x
    puts i
end

#A
#1
#b
#3

Consecutive numbers


for i in 0..3
    puts i
end

#0
#1
#2
#3

each do Repeat with the esch method. `object.each do |variable|Processing end`

python


arrays = ["A", 1, "b", 3]

arrays.each do |array|
    puts array
end

#A
#1
#b
#3

while Repeat within the condition range. `while conditional expression processing end`

python


i = 0

while i < 3
    puts i
    i += 1
    # i++Cannot be used
end

#0
#1
#2

times do Specify the number of repetitions. `Numerical value.times do |variable|` ┗ The index number is entered in the variable (starting from 0)

python


3.times do |i|
    puts "#{i}This is the second process"
end


#This is the 0th process
#This is the first process
#This is the second process

loop + break Repeat with a combination of infinite loop and end condition. `loop {processing if condition break end}` ┗ Error if there is no end condition (break)
i = 0 

loop{
    puts i
    i += 1
    
    if  i >=3
        break
    end
}

#0
#1
#2
#3

### Skip (if next) Only the specified condition is skipped. ʻIf conditional expression next end` ┗ Used in iterative processing.

python


3.times do |i|
    if i == 1 
        next
    end

    puts "#{i}This is the second process"
end

#This is the 0th process
#This is the second process

## Creating and calling methods

▼ Creation def method name () processing end ┗ () is not required when there is no argument.

▼ Call Method name ()

python


def hello(name)
    puts "Hello #{name}Mr."
end

hello("Yuta")

#Hello Yuta

▼ Case 2

Multiple arguments


def ttl_price(price, n)
    return (price * n * 1.10).floor  #return is optional
end

puts ttl_price(500, 3)

#1650

## Creating a class and creating an instance ### Creating a class

class class name end

--Class names are capitalized. --Initialize method: A method that is automatically called when an instance is created. --Properties are defined by @.

Creating a class


class User
    def initialize(name)
        @name = name
    end

    def say_name
        puts "I#{@name}is."
    end

end

## Instance generation

Variable = class name.new (argument)

Instance generation


tanaka = User.new("tanaka")
tanaka.say_name

#I'm tanaka


yamada = User.new("yamada")
yamada.say_name

#I'm yamada

that's all.

Recommended Posts

[Ruby] List of basic commands
Basic methods of Ruby hashes
Basic methods of Ruby arrays
Review of Ruby basic grammar
Basic knowledge of Ruby on Rails
Gem list of each ruby version 2.5.x
Ruby basic terms
Docker basic commands
Basics of Ruby
[Ruby] Basic knowledge of class instance variables, etc.
[Note] A list of commands that I checked many times after trying Ruby.
Ruby learning points (basic)
ruby basic syntax memo
List of beginners (List) memo
Basic format of Dockefile
definition of ruby method
ruby memorandum (basic edition)
[Ruby] Basic code list. Keep the basics with examples
List of things I used without understanding well: Ruby
List of Docker commands that I often use (container operation)
Basic knowledge of SQL statements
Review the basic knowledge of ruby that is often forgotten
[Ruby] Various types of each
[Docker] Introduction of basic Docker Instruction
Ruby on Rails basic learning ①
Delete all the contents of the list page [Ruby on Rails]
[Java] Basic summary of Java not covered by Progate ~ Part 2 · List ~
I tried to summarize the basic grammar of Ruby briefly
Super basic usage of Eclipse
Judgment of fractions in Ruby
List of hosts file locations
Summary of basic functions of ImageJ
Ruby methods and classes (basic)
Ruby on Rails Basic Memorandum
About the behavior of ruby Hash # ==
[Java] Delete the elements of List
Understand the basic mechanism of log4j2.xml
Enumeration of combination patterns using List
[Rails] List instances of multiple models
Basics of sending Gmail in Ruby
Implementation of ls command in Ruby
[Ruby] See the essence of ArgumentError
A list of rawValues for UITextContentType.
The basic basis of Swift dialogs
Basic usage of java Optional Part 1
Summary of frequently used Docker commands
Official logo list of the service
Ruby 5 or higher sum of integers
Memorandum (Ruby: Basic grammar: Iterative processing)
List of members added in Java 9
Basics of Ruby ~ Review of confusing parts ~
Ruby / Rust linkage (6) Extraction of morphemes
Impressions of making BlackJack-cli with Ruby
Basic processing flow of java Stream
Ruby memorandum (acquisition of key value)
[Ruby] Review about nesting of each
List of types added in Java 9
Explanation about Array object of Ruby
List of alternative distributions for CentOS
[Basic knowledge of Java] Scope of variables
Ruby Basics 2 ~ Review of confusing parts ~