[Ruby] Writing notes for cherry books [Notes for yourself]

what's this

This is an article that I just read a Ruby cherry book and copied and pasted a note with a note of my impressions **. ** I didn't write it with the intention of telling people **, so I'm sorry, but please understand. The purpose is to create an index in my head.

Chapters 1 to 4

ruby can be a variable name in kanji or hiragana. But basically I don't do it.

If you enclose it with%!%, It will be like enclosing it with single or double quotes.

Here-documents are used when writing long strings or newline characters. For example, writing SQL in solid.

Why is it recognized as a single character string when I write "? A"?

All Int and Float numbers are subclasses of Numeric.

Since it is calculated in binary, there is a wraparound problem.

The default arguments can be methods or Time.now.

Methods ending with "?" By convention return boolean values

For methods ending with "!", Write a process that returns an error or pays attention. There is also the practice of destructive methods.

A method that changes the state of the called object is called a destructive method.

If you end the variable name with "!" And "?", You will get an error.

Alias ​​methods are the same implementation but different names. You can choose whatever you like

There is an expression (assign the return value to a variable) and a statement (no return value)

You can see the object ID with a.object_id. The assigned one is a reference assignment, so the ID is the same

puts and print are displayed by to_s, for general use. p is a developer display called the inspect method

When assigning to an array, if you skip the number, it will be filled with nil

delete_if is also an alternative to each

Range object (range) The conditions are different for 2 or 3 periods. Whether to include or not include the last

You can take the end of the array with the last method and specify "get the number from the end" as an argument. first

"|" Is the intersection

"-" Finds the set of differences. Remove the elements contained in the right array from the left array [1,2,3]-[3,4,5] = Return value: 1,2

"&" Is the intersection

There is a class that handles a set called set class

If you want to expand the array and pass it as "multiple arguments", put "*" in front of the array. There are various uses

An unlimited number of arguments are called variadic arguments.

It can be handled as an array of character strings with "% w (a b)". Spaces are treated as line breaks. If it is "% i", it becomes a symbol. The meaning of the words w and i is unknown

Mutable = variable, immutable = immutable

There is also a map.with_index method like each_with_index. With .each.with_index, if you pass argument 1, it will start from 1. On the contrary, if it is _, it cannot be passed.

When passing an argument in an array, it can be expanded and written by writing the argument of the content statement of the array. When it sticks out, nil The first argument is the array to expand. The second argument is index. First, if you expand in (), you can expand and each

File.open("./sample.txt", "w") do |file|

It's amazing that you can write it in a file with this. I knew it for the first time.

do..end and {} have different couplings ➡️ Priority issue. "()" Is required for "{}" with argument ➡️ But it doesn't happen because I add the basic (). There is such a specification, it's about

Arrays have a lot of APIs. Read the document first, rather than writing the process you want to do yourself

It can be processed for each array by join after map. ruby version method chain

You can play with the array of numbers with upto and downto!

There is also a while negative sentence (like unless) called until

The feature of the for statement of ruby ​​is that the variables defined in the for statement can be used outside the for statement! !! Be aware of the difference between using blocks

There is a loop method that repeats for a lifetime

You can put a while statement in a variable. And break can have arguments. Hierarchy break only exits that hierarchy

A man who absolutely comes out with throw catch. Argument with a symbol. Tag

ruby implicitly returns the last evaluated value (return)

Break and return have completely different processes and roles

Next to skip to the next process, redo to redo

Chapter 5

Comparison between hashes, true changes even if the order of key values ​​is different. False if any value is different

This will change the value of the key when it fails. This time japan1

p a.delete('japan1'){ |key| "hoge: #{key}"}

Obviously, hashes and symbols are different. Symbols are treated internally as integers

Symbols are immutable objects

The keyword argument is something like def test (hoge: “fuga”) end // test (hoge: “piyo”)

Hash can be expanded with two asterisks

You can get the hash as a keyword argument with options = {}. It is called a pseudo keyword argument. Arguments that never cause an error (nil is returned). But this kind of expression seems convenient, but I don't really like it. Not recommended.

** Others can take arbitrary hash arguments in addition to keyword arguments

Can be made into an array or hash with to_a (array) and to_h (hash)

You can manipulate hashes and arrays with Hash [variable name] and Array [variable name]

When you have.new, if you return it as a block argument with "{}" in curly braces instead of "()", the object_id will change every time.

With this, the added code will have more and more arguments.

h=Hash.new {|hash,key| hash[key]='hello'}
p h
p h[:foo]
p h[:bar]
p h

Character strings can be expanded even with symbols!

p :"#{name.upcase}"

The respond_to? method returns a boolean value indicating whether the method can be used.

p 'apple'.respond_to?('include?') # true

The if statement checks the return value, so the two have the same meaning. I like the former because it's complicated whether it's a conditional comparison or a substitution.

def a(b)
  c={japan: 'yen'}
c=a(:japan) #With this
if c = a(:japan) #This has the same meaning
  c.upcase #This if statement and upcase are the same
c = c&.upcase #This if statement and upcase are the same (Bocchi operator)
puts c

「||=Is self-assignment. If it is nil or false, substitute the right side. a+=Reason similar to 1. a= a ||Is it like 1?

a = nil
p a ||= 10 # 10
b = 1
p b ||= 10 # 1

"!!" of the image that repeats twice

p !!true # true
p !!1 # true
p !!false # false

The following two examples have the same meaning. Roles so

def user_exists?
  # user = "a"
  # if user
  #   true
  # else
  #   false
  # end

  !!true #true changes
  !!false #false changes
p user_exists?

6 Regular expression

A site where you can test ruby ​​regular expressions https://rubular.com/

\d Metacharacters. Match half-width numbers

JavaScript "g"

Global option. With g = All matching character strings. No g = 1 hit ends

You can see the regular expression with "■ *" of command + F of vscode!

Find the string pattern!

{n,m} Specify a character string. It's called Quantum Teishi.

[AB] One letter of either A or B

[a-z] Letters from a to z

[09-] Search for 0 or 9 or --. It changes a lot depending on the position of the hyphen!

[] You can also use blank space characters (half-width, full-width)!

? Or none

. Any single letter

One or more characters immediately before

() The enclosed part is captured and numbered sequentially. Will it be treated differently? ??

$ Extract the part enclosed in (). Like $ 1, $ 2

There are 0 or more arbitrary (immediately before) characters. 0 is included

?: Do not group

\w Same meaning as [a-zA-Z0-9_]. You don't have to enclose it in []. Repeat the same character with \ w +

^ Example) [^ a]: Any character other than A

(.*?) Returns the shortest match as a result. The smallest quantum constant

\n Newline character. If you specify it with a regular expression, it will delete each line and pack it!

| or condition

=~ Condition comparison of ruby. Returns the number of matching characters + returns nil if there is a mismatch (ie false)

match Returns a match & grouped array. Array. It can be taken with m [0].

(?\d) Metacharacters. Can be taken as a symbol or character string

Application ⬇️

if /(?<year>\d+)Year(\d)Moon(\d)Day/ =~ text
  puts year # year

However, you must always put the regular expression on the left. Is the variable useless?

scan Returns a match. Array when grouped

[ ] You can write regular expressions. You can use anything as basic

text = '123-45'
p text[/(\d{3})(-)/, 2]

slice Alias ​​method for [] slice! Is destructive

split You can write the place to separate with a regular expression

t = '123,456-789'
p t.split(/,/)

gsub Replace

t = '123,456-789'
p t.gsub(/(,).+(-)/, '\1fuga\2hoge') # "123,unko-hoge789"

t = '123,456-789'
p t.gsub(/(?<fuga>,)(\d+)/, '\k<fuga>fuga\1aaa') # "123,fugaaaa-789"

t = '123,456-789'
hash = { ',' => ":::::" }
p t.gsub(/,/, hash)

t = '123,456-789'
p t.gsub(/,/) { |m| m == ',' ? '::::' : '//////'}


# p 'HELLO' =~ /hello/i #Ignore case
# regexp = Regexp.new('hello', Regexp::IGNORECASE)
# p 'HELLO' =~ regexp
# p "Hello\nBye   #hoge" =~ /Hello.Bye/xm #Comment and line breaks.Recognized by
text = "1977"
text =~ /(\d+)Year/
p $~ # #<MatchData "1977" 1:"1977">
p $& # "1977"
p Regexp.last_match(1) # "1977"

It seems that those starting with $ are called built-in variables

Chapter 7 class

Reasons to use classes: Because they are robust. Because the value cannot be rewritten without permission?

Synonymous with class object = instance

Sometimes called receiver and message. In the following cases, user is the receiver Can be expressed as sending the message first_name

user = User.new('Bob', 'Python', 30)

attr_accessor allows reading and writing of objects.

# attr_If there is no accessor
a.first_name = 'Alice' # undefined method `first_name
# attr_With accessor
a.first_name = 'Alice' # Alice 代入できる!

private is automatically given to initialize. private The following methods are called private method full_name' called`

Local variables may start with an underscore

Accessing a non-existent instance variable returns nil

If you prepare the following method, you can assign it to an instance variable though it looks like a method

  def name=(v)
    @name = v

attr_reader is read-only, attr_writer is write-only

a.name = ('2') #writer
p a.name # reader

Trivia: Classes can be overwritten

Internal data differs depending on the instance

Instance method

Instance methods can be used for a, such as a = User.new

You can also declare a class method by doing class << self \ n class method. I don't need self here. But it seems uncommon

It makes a big difference whether you assign it to a local variable or an instance variable of a class.

a = User.new("hoge")

  def name1
    name = '1'
p a.name # “hoge”

  def name2
    self.name = '2'
p a.name # “2”

Class methods cannot be called from instance methods On the contrary, the instance method cannot be called from the class method.

As an extreme example, you can call a class method when creating a class. But once instantiated, it can't be called. If you want to make changes for each instance of the instance method (save !, etc.) Class methods are when you want to make changes to all your data (all, search, or anything that affects the whole thing)

Class name in instance method. Once class method (self), you can call class method for the time being

Inheritance, subclass is a kind of superclass (is-a) DVD is a Product?

All inherit from the Object class. So you can use to_s and nil? In the generated class.

Digression: If you super with the overridden method, it will be output on one line> <

Private methods cannot be called from outside the class because they cannot be called by specifying the receiver (user).

Private methods can be overridden by inheriting them.

Class methods don't work private, but you can make them private with << self. There is also a magic called private_class_method.

protected can be called from the instance method of the receiver (user). I get an error when I call it directly. Private can't even set the receiver, but protected can be called based on the receiver! !! !!

Constants cannot be created inside a method. Always directly under the class syntax

If it is an array or the order is specified, even a constant will be reassigned. Be careful about freeze and so on!

How to set an alias

alias new_method old_method

You can delete a method with undef

Method call while assigning to variable

a.old_method = "value"

See object_id for equal? == Is the content of the object correct? eql? sees if the hash key is different === is used in when for cases

ruby has no restrictions on class inheritance

Monkey patch to overwrite existing implementation and return behavior

Singular methods (def alice.hello) etc. that are associated with a specific object

Class methods are actually singular methods. Because I specify the class itself with self

I'm duck typing

Chapter 8

You cannot create an instance from a module Cannot inherit other modules or classes


If it is ruby, add a module to the class. The types of include and extend are irrelevant

Modules can also use private methods!

It can be used as a singular method (class method) with extend. You can't use it without self!

all? method. True if all are true. Seems to have block arguments

It seems that include allows the method to the module destination to the instance. You can use the mixin method on the receiver.

There is an Enumerable module. This guy has a map or find!

The Comparable module has operators. You can change it to your favorite operator by including it <=> has the key! It seems to be a UFO operator

self inherits main class

Object includes the Kernel module. So you can use puts method in all!

You can extend a module to a specific instance

A class can only inherit one parent. Multiple modules can be inherited

You can create a class inside a module.

If you use the module function method, you can use it as a mixin & singular method! ?? But it becomes a private method

However, if you mixin with another class, it becomes a private method.

Modules cannot be instantiated.

You can see in what order the methods are searched by the ancestors method.

The method of the module included by prepend has priority

It changes depending on the order of calling. Returns the first one found. Same as find_by The calling position changes the moment you prepend!

You can specify the range of methods with refine

You can use method calls with either :: (colon) or . (dot)

9 Exception handling

Exceptions can be thrown anywhere, but you have to operate within the appropriate range

If you write the class name after rescue, you can catch the error of that class!

rescue NoMethodError => e

NoMethodErrpr inherits NameError, so you can catch it with rescue NameError You can catch anything if it is an inherited class. StandardError or the main Exception class

You can restart even if an exception occurs with retry. Be careful as it tends to be an infinite loop

Throw an exception with raise. An error message is attached.

Don't use rescue easily. An unexpected error is born. Basically leave it to abnormal termination or common processing

Narrow the scope of exception handling (between begin and rescue). Because the cause range is small and debugging becomes easier

Should I check for arguments-only errors?

Conditional branching may include performance rather than exception handling. Read the document

With ensure, processing can be executed at either normal termination or exception.

Perform processing when an exception does not occur in else

Exception handling also has a return value. It seems that ensure is just output and there is no return.

If you return with ensure, it will be the return value. Never do it!

10 What is yield proc?

If you use yield, you can use it by fetching the block as an argument It throws an error when yield is called without a block You can have an argument in yield returns true or false with block_given?

proc is a class for objectifying blocks. You can call it with call. You can also use the proc method & Is required to pass a proc object as an argument. On both the handing side and the receiving side. ➡️ Can be omitted!

block.call will be nil if there are no arguments.

However, the argument check is strict for the following two. If they do not match, an error will occur.

proc = ->(a,b){ a+b }
proc = lambda { |a,b| a+b }

There is a method called to_proc that is doing well behind the scenes.

The reason why the following two output results are the same

p ['Ruby', 'Java', 'Perl'].map { |s| s.upcase }
p ['Ruby', 'Java', 'Perl'].map(&:upcase)

Receive a block argument with &. The to_proc method works behind the scenes with the symbol : upcase. Variable passed in the block? Upcase method applied & returned to The reason that upcase can be applied is that there are no arguments (?)

Proc.new stops all processing when it returns or breaks lambda goes through the processing loop and proceeds with the next processing. There is this difference

11 Debug technique

The bottom of the back trace is old. You can write it above and it will be new. I want the bottom to be important It's rudimentary, but let's go through the error logs in order from the bottom. Because the logs are output in the order of the executed methods!

By the way, NameError is the parent class of NoMethodError.

SystemStackError is more likely to occur in recursive situations I often see these days

tap debug. The block argument is returned as it is as a return value.

a='hello'.split('').tap{|s|p s}.join('-').tap{|s|p s}

It seems that the return value of the p method is also the output value, so there is no problem even if you insert it in the middle. The puts method is useless because the return value is nil. Ah ~

The Rake command is suitable for executing a set of processes (tasks).

Explained in desc, namespace can also be used. ":" One colon is ok

Recommended Posts

[Ruby] Writing notes for cherry books [Notes for yourself]
Docker related commands (notes for yourself)
Ruby vertical writing
Ruby Hash notes
Annotation notes when writing tests for Spring Boot
Writing code Ruby
[For Ruby beginners] Ruby engineer certification exam Silver/Gold exam notes
abbreviation for ruby method
Ruby Thread # [] = method notes
Notes for AST analysis
Ruby Learning # 27 Writing Files
Ruby study notes (puts)
Ruby cherry book review
Ruby Learning # 23 For Loops
Scraping for beginners (Ruby)