[Ruby] Basic code list. Keep the basics with examples

[Ruby] Basic code list. Keep the basics with examples

A list of basic ruby items for memorandum.

If you remember puts, hashes, symbols, how to write each method, and elsif of if expression, the rest is almost the same as other languages.

table of contents

  1. Extension (.rb)
  2. [Output (puts method)](# output puts method)
  3. [Comment out (#)](#Comment out)
  4. [Connect letters (+)](#Connect letters)
  5. [Variable definition (=)](#Variable definition)
  6. [Self-assignment operator](# self-assignment operator)
  7. [Expression expansion ("# {}")](# Expression expansion)
  8. [if expression (conditional branch)](# conditional branch)
  9. [Comparison Operator](#Comparison Operator)
  10. [Logical Operators](#Logical Operators)
  11. [Array](# array)
  12. [each method (repetitive processing)](#each method iterative processing)
  13. [Symbol (: value)](# symbol)
  14. Hash
  15. [Update Hash Value](# Update Hash Value)
  16. [Add element to hash](#Add element to hash)
  17. [Use symbols for keys](Use symbols for # keys)
  18. [Symbol-based abbreviation](#Symbol-based abbreviation)
  19. nil
  20. [nil and hash](#nil and hash)
  21. [nil and if expression](#nil and if expression)
  22. Arrays and hashes (#arrays and hashes)
  23. [Retrieve the hash value in the array](# Extract the hash value in the array)
  24. Use the each method to retrieve the hash value (use the #each method to retrieve the hash value)
  25. [Hash / each method / if expression combination](#hash each method if expression combination)

## extension `.rb`

Output (puts method)

puts "AAA" └ "'" is OK └ Half-width space required after puts

Comment out (#)

#

Connect letters (+)

puts 'AAA' + 'BBB' └ Numerical values and character strings cannot be concatenated └ Unify types (or variable expansion)

Variable definition

Variable name = number Variable name ='string'

Self-assignment operator

x=x+10x+=10 x=x-10x-=10 x=x*10x*=10 x=x/10x/=10 x=x%10x%=10

Expression expansion

puts "#{ }" └ Double quotation └ * Single quotation is output as a character string as it is

python


hello = "Hello"
name = "AAA"

puts "#{hello}、#{name}Mr."

Variable expansion of python and php. In ruby, it is called expression expansion.

if expression (conditional branch)

python


if conditional expression 1
processing
elsif conditional expression 2
processing
else
processing
end

└ elsif (python:elif, php: else if) └ Conditional expression is replaced with true / false └ If false, skip processing

Comparison operator

== equal ! = Not equal Greater than > Smaller than < > = or more <= Below

Logical operator

&& and ||Or

Array

[Element 1, Element 2, Element 3, ,,,]

python


array = ["AAA","BBB","CCC"]
puts array[0]
puts "The element of index number 1 is#{array[1]}is."

#output
AAA
The element with index number 1 is BBB.

each method (repetitive processing)

python


Array.each do |Variable name|
processing
end

.each do| | └ Finally ʻend` required └ The defined variable name can be used only in each method.

Example of use


elements = ["AAA","BBB","CCC"]
elements.each do |element|

puts "The contents of the array#{element}is." 

#output
The contents of the array are AAA.
The contents of the array is BBB.
The contents of the array are CCC.

symbol

: Value └ Symbol type └ Can be used as a substitute for character strings └ Often used as a hash key

python


puts "AAA"
puts :AAA

#output
AAA
AAA

hash

The name of the array with each value given a name (key). {Key 1 => Value 1, Key 2 => Value 2, Key 3 => Value 3, ,,,} └ Enclose the character string in "" "(key, value) └ Braces: {} └ Assign a hash to the array

Hash example


elements = {"key1"=>"A","key2"=>"B", "key3"=>"C"}
puts elements["key2"]

#output
B

** ▼ Other languages ** ・ Python dictionary type {Key 1: Value 1, Key 2: Value 2, Key 3: Value 3, ,,,} ・ Php associative array (Key 1 => Value 1, Key 2 => Value 2, Key 3 => Value 3, ,,,);

Hash value update

Hash ["key name "] = value you want to change

Hash example


elements = {"key1"=>"A","key2"=>"B", "key3"=>"C"}
elements["key2"]=222

puts elements["key2"]

#output
222

Add element to hash

python


elements = {"key1"=>"A","key2"=>"B", "key3"=>"C"}
elements["key4"]="D"

puts elements

#output
{"key1"=>"A","key2"=>"B", "key3"=>"C", "key4"=>"D"}

Use symbols for keys

The key name can be represented by adding ":" instead of a character string. : Key name => value └ Acquisition array [: key name]

python


elements = {:key1=>"A",:key2=>"B", :key3=>"C"}
puts elements[:key2]

#output
B

Abbreviations with symbols

: Key name => valuekey name: value └ * Use symbols when acquiring └ Acquisition array [: key name]

Symbol (abbreviation)


elements = {key1:"A",key2:"B", key3:"C"}
puts elements[:key2]

#output
B

nil nil └ Empty elements └ When nil itself is output, it becomes an empty string

nil and hash

--If you specify a key that does not exist, the value will be nil. --No error

nil


elements = {key1:"A",key2:"B", key3:"C"}
puts elements[:key4]
puts nil

#output


nil and if expressions

In addition to true and false conditional expressions, if expressions can use nil or others.

・ Nil → false ・ Other than nil → true

python


elements = {key1:"A",key2:"B", key3:"C"}

if elements[:key4]
 puts "The value of key4 is#{elements[:key4]}is"
else
 puts "There is no key4"
end

#output
There is no key4

Arrays and hashes

Put a hash in the elements of the array

You can put hashes in the elements of the array.

python


elements = [{order:"A",number:1}, {order:"B",number:2}, {order:"C",number:3}]

Arrange with line breaks


elements = [
  {order:"A",number:1}, 
  {order:"B",number:2}, 
  {order:"C",number:3}
]

puts elements[0]

#output
{order:"A",number:1}

Fetch the hash value in the array

python


elements = [
  {order:"A",number:1}, 
  {order:"B",number:2}, 
  {order:"C",number:3}
]

#Assign to a variable and retrieve
element = elements[0]
puts element[:order]

#Extract in one line
puts elements[0][:order]

#output
A
A

Use each method to retrieve the hash value

each


Array.each do |Variable name|
processing
end

each and hash


elements = [
  {order:"A",number:1}, 
  {order:"B",number:2}, 
  {order:"C",number:3}
]

elements.each do |element|
  puts "#{element[:order]}The numbers are#{element[:number]}is"
end

#output
The number of A is 1
B number is 2
The number of C is 3

A combination of hash, each method, and if expression

python


elements = [
  {order:"A",number:1}, 
  {order:"B"}, 
  {order:"C",number:3},
  {order:"D"}
]

elements.each do |element|
 #Determine if there are numbers
  if element[:number]
    puts "#{element[:order]}The numbers are#{element[:number]}is"
  else
    puts "#{element[:order]}There are no numbers"
  end
end

#output
The number of A is 1
There is no B number
The number of C is 3
There is no D number

The way to write each method is unique and interesting. The merit of adding do and enclosing the variable name with a pipe is mysterious.

Recommended Posts

[Ruby] Basic code list. Keep the basics with examples
Feel the basic type and reference type easily with ruby
Feel the basic type and reference type easily with ruby 2
Format Ruby with VS Code
[Ruby] List of basic commands
Understand code coverage with Rspec, the Ruby on Rails test framework
Programming with ruby (on the way)
[Ruby] I tried to diet the if statement code with the ternary operator
With ruby ● × Game and Othello (basic review)
Introduction to Ruby basic grammar with yakiniku
[Ruby] From the basics to the inject method
Basic usage of enums and code examples
Ruby basics
Ruby basics
Ruby basics
[Ruby] Summary of class definitions. Master the basics.
A memorandum to clean up the code Ruby
Publish the app made with ruby on rails
Manage the version of Ruby itself with rbenv
[Competition Pro] Solve the knapsack problem with Ruby
[Ruby] Code to display the day of the week
How to write test code with Basic authentication
[Ruby] Exclude duplicate elements with the uniq method.
Determine the current page with Ruby on Rails
Finding pi with the Monte Carlo method? (Ruby)
I checked the number of taxis with Ruby
[Ruby basics] How to use the slice method