Review of Ruby basic grammar

This is a memorandum of points that I thought were important and techniques I didn't know when I was reviewing with different teaching materials after completing the basic learning of Ruby.

.class and .methods (available for objects)

Destructive method (with!)

A method that rewrites the original value (Example) .upcase method (output with the value changed to uppercase) name = "tarou"

puts name.upcase #"TAROU" puts name #=>"tarou"

puts name.upcase! #"TAROU" puts name #=>"TAROU"

Check the truth value (with?)

name = "tarou" p name.empty? #false p name.include?("r") #true

Array subscript

--Minus numbers [-1] is the first from the end [-2] is the second from the end

--Range specification If you specify [0..2], you will get a value between 0 and 2. [0 ... 2], just before 0-2

Frequently used methods for hashing

--size ・ ・ ・ Get the number of elements (can be used in an array) --keys ・ ・ ・ Get a list of keys --values ​​・ ・ ・ Get a list of values --has_key? ("name") ・ ・ ・ Whether there is a key

conversion

--to_i ・ ・ ・ Integer (integer) --to_f ・ ・ ・ with decimal point (float) --to_s ・ ・ ・ Character string (string) --to_a ・ ・ ・ Array --to_h ・ ・ ・ Hash

(Example) Conversion of array and hash scores = {taguchi: 200, fkoji: 400} scores.to_a => [[:taguchi, 200], [:fkoji, 400]] scores.to_a.to_h => {:taguchi=>200, :fkoji=>400}

%notation

--Single quotation 'Character string' ・ ・ ・ Can be written with% q (character string)

What is convenient?

Easy to understand when you want to write double quotes or single quotes in a character string

If you want to write [he \ "llo]" => puts "he"llo" => puts %Q(he"llo) => puts %(he"llo)

If you want to write ['he 'llo'] => puts 'he'llo' => puts %q(he'llo)

[% Notation for arrays]% W or% w 【p ["red", "blue"]】 => p %W(red blue)

【p ['red', 'blue']】 => p %w(red blue)

Iterative processing using for

for is an instruction that can repeat some processing for the number of elements of some collective object (array or hash) or object representing the range.

for i in 10..20 do
  p i
end

#Can be rewritten to each
(10..20).each do |i|
  p i
end
for color in ["red", "green"] do
  p color
end

#Can be rewritten to each
["red", "green"].each do |color|
  p color
end
for name, score in {taro:100, jiro:200} do
  puts "#{name}: #{score}"
end

#Can be rewritten to each
{taro:100, jiro:200}.each do |name, score|
  puts "#{name}: #{score}"
end

Classes (class methods, class variables, constants)

--Class method def self. method name end

--Class variables @@Variable name

--Constant Start with a capital letter (customarily written in all capital letters)

(Example)
class User

  @@count = 0 #Class variables

  VERSION = 1.3 #constant

  def initialize(name) 
    @name = name
    @@count += 1
  end

  def sayHi #Instance method
    puts "hi! i am #{@name}"
  end

  def self.info #Define class method
    puts "#{VERSION}: User Class, #{@@count} instances."
  end

end

ichiro = User.new("ichiro")
jiro = User.new("jiro")
saburo = User.new("saburo")
User.info #Execution of class method (can be called directly from the class)
p User::VERSION #When calling a constant from outside the class, write two colons

Class inheritance

class Miniuser <User (User class information is inherited) User: Called parent class or Super Class MinUser: Called a child class or Sub Class

It is also possible to overwrite the method defined in the parent class in the child class (called override)

private point (method access right)

--Receiver cannot be specified --Can be called from Sub Class (child class) (feature of Ruby) --Can be overridden (feature of Ruby)

About modules

When the development scale becomes large, the method name etc. may be covered with the one created by another person, which may cause an error. In such cases, using modules is convenient because the named names do not conflict. A feature of modules is that they can group methods and constants, but they cannot generate or inherit instants.

#How to make a module
module Car #Start with a capital letter

  VERSION = 1.3 #Can make constants

  def self.go
    puts "going..."
  end

  def self.stop
    puts "stopping..."
  end

end

#Module execution
Car.go
Car.stop

About the module Part 2

There is a mixin for the purpose of the module. Used only when providing to a class as a function. When a method is created, it can be used as an instance method of another class by making it an instance method without adding self, and this is called a mixin. At that time, describe "include module name" on the class side.

Recommended Posts

Review of Ruby basic grammar
Basic methods of Ruby hashes
Basic methods of Ruby arrays
[Ruby] List of basic commands
Ruby Review 2
Ruby Review 1
Extraction of "ruby" double hash * Review
Basic knowledge of Ruby on Rails
Memorandum (Ruby: Basic grammar: Iterative processing)
Basics of Ruby ~ Review of confusing parts ~
Ruby Basics 2 ~ Review of confusing parts ~
Review the basic knowledge of ruby that is often forgotten
I tried to summarize the basic grammar of Ruby briefly
With ruby ● × Game and Othello (basic review)
Ruby basic terms
Java basic grammar
Introduction to Ruby basic grammar with yakiniku
Java basic grammar
Basics of Ruby
Memorandum (Ruby: Basic Grammar: Classes and Instances)
Java basic grammar
[Ruby] Basic knowledge of class instance variables, etc.
Java engineers now compare to learn the basic grammar of Ruby Part 1 (Basic, Variables)
Ruby learning points (basic)
Review of java Shilber
ruby basic syntax memo
Basic format of Dockefile
definition of ruby method
Ruby cherry book review
NIO review of java
ruby memorandum (basic edition)
Java review ① (development steps, basic grammar, variables, data types)
Memorandum (Ruby: Basic grammar: Use by naming the process)
Basic knowledge of SQL statements
[Ruby] Various types of each
[Docker] Introduction of basic Docker Instruction
Ruby on Rails basic learning ①
Super basic usage of Eclipse
Judgment of fractions in Ruby
Summary of basic functions of ImageJ
JavaScript overview and basic grammar
Ruby on Rails Basic Memorandum
Memorandum (Ruby: Basic grammar: Iterative processing)
Basic processing flow of java Stream
[Java] Exception types and basic processing
About the behavior of ruby Hash # ==
Implementation of ls command in Ruby
The basic basis of Swift dialogs
The basic basis of Swift's Delegate
Basic usage of java Optional Part 1
Ruby 5 or higher sum of integers
Ruby / Rust linkage (6) Extraction of morphemes
Basic processing flow of java Stream
Ruby memorandum (acquisition of key value)
[Basic knowledge of Java] Scope of variables
[Ruby] Display the contents of variables
Basic structure of Java source code