Ruby from the perspective of other languages

Introduction

Ruby Part 2 Advent Calendar 2020 Day 15 Article! !!

Around the fall of this year, Ruby Association Examination Was received.

While studying for the exam at that time, there were just things like "Do you write this in Ruby?" Or "Does this mean in Ruby?", So I will introduce it really lightly! !!

(I don't know much at all, so please try more ...)

Click here for teaching materials when studying. If you are interested, please try it! !! https://gist.github.com/sean2121/945035ef2341f0c39bf40762cd8531e0

begin ~ resucue

Speaking of Ruby exception handling, this is it. The error that occurred in the begin block is picked up by resucue and error handling is performed.

begin
  1 / 0
rescue ZeroDivisionError => error
  p error
end

# => #<ZeroDivisionError: divided by 0>

In other languages, I think most of them are try ~ catch.

try {
  nonExistentFunction();
} catch (error) {
  console.error(error);
}

// > ReferenceError: nonExistentFunction is not defined

Try and catch in Ruby

try

Ruby also has try, but it's a method for objects, not exception handling methods. https://www.rubydoc.info/docs/rails/4.1.7/Object:try

Try in Ruby is ** almost ** synonymous with & .. (&. Is often called ** nil guard **.) ** "Almost" **, so there are a few differences.

&. Calls the method if the object is not ** nil. ** ** try calls a method when the object's ** method can be called. ** **

# &.
10&.to_s        # => "10"
10&.hoge        # => Error: undefined method `hoge' for 10:Fixnum (NoMethodError)
nil&.to_s       # nil

# try
10.try(:to_s)   # => "10"
10.try(:hoge)   # => nil
nil.try(:to_s)  # => nil

catch

Catch in Ruby can be exited if it matches its argument when throw runs in the block. It is one set with throw ~ catch.

catch :error do
  puts "hoge"
  throw :error
  puts "fuga"
end
# => hoge

This is similar to begin ~ rescue, but quite different. Click here for details. https://qiita.com/harvath/items/e716179538bc1da30f88

It's more like C language goto than exception handling.

*variable

For those who write C or Go, the * variables are pretty familiar.

Everyone loves it, ** pointer **!

tour_of_go.go



import "fmt"

func main() {
	i, j := 42, 2701

	p := &i         
	fmt.Println(*p) 
	*p = 21         
	fmt.Println(i)  

	p = &j         
	*p = *p / 37   
	fmt.Println(j) 
}

/*
42
21
73
*/

The pointer points to the ** value memory address **. To put it simply, it looks like this. (Example: go)

i := 42
p := &i
	
fmt.Println(p)  // 0xc000122020
fmt.Println(&p) // 0xc000124018
fmt.Println(*p) // 42

fmt.Println(i)  // 42
fmt.Println(&i) // 0xc000122020
fmt.Println(*i) //Get an error
variable value アドレスvalue
i i = 42 &i == p = 0xc000122020
p *p == i = 42 &p = 0xc000124018

Click here for pointers. https://qiita.com/yz2cm/items/01908cdfe56c304f2a14

However, * variables in Ruby are not ** pointers! !! ** (When I first learned about it, I misunderstood that it was a pointer ...)

In Ruby, it is ** an array of variables **. In other words, it has the same meaning as the to_a method. When attached to a method keyword argument, it can be used as a ** variadic argument **.

def foo (a, *b)
  p a, b
end

foo(1, 2, 3, 4)

# => 1
# => [2, 3, 4]

**variable

By the way, in Ruby you can also write ** variables. This often means Hash.

def variadic_keyword(**hash_args)
  p hash_args
end

variadic_keyword(april:"spring", july:"summer")

# => {:april=>"spring", :july=>"summer"}

At the end

It's really easy and light! !!

I think there are many other things, so I will update them each time. (Please do not ask for the test results ...)

Recommended Posts

Ruby from the perspective of other languages
Introduction to Ruby (from other languages)
How to write Scala from the perspective of Java
About the usefulness of monads from an object-oriented perspective
Java language from the perspective of Kotlin and C #
About the behavior of ruby Hash # ==
[Ruby] See the essence of ArgumentError
[Ruby] Display the contents of variables
Let's summarize the Java 8 grammar from the perspective of an iOS engineer
[Challenge CircleCI from 0] Learn the basics of CircleCI
[Ruby] From the basics to the inject method
part of the syntax of ruby ​​on rails
The story of RxJava suffering from NoSuchElementException
[Ruby] Cut off the contents of twitter-ads
Find the difference from a multiple of 10
Iterative processing of Ruby using each method (find the sum from 1 to 10)
Comparison of nullable, non-nullable, non-nullable and safe types from the perspective of null safety
How to find the cause of the Ruby error
[Ruby] Summary of class definitions. Master the basics.
[Promotion of Ruby comprehension (1)] When switching from Java to Ruby, first understand the difference.
[Ruby on Rails] Until the introduction of RSpec
[Delete the first letter of the character string] Ruby
The story of introducing Ajax communication to ruby
Manage the version of Ruby itself with rbenv
Basics of Ruby
[Ruby] Code to display the day of the week
I checked the number of taxis with Ruby
ArrayList and the role of the interface seen from List
Count the number of occurrences of a string in Ruby
From the introduction of devise to the creation of the users table
JavaFX --Match the size of ImageView with other nodes
Volume 3 types of Docker Compose considered from the purpose
[Ruby] The role of subscripts in learning elements in arrays
Docker the development environment of Ruby on Rails project
[Ruby] How to find the sum of each digit
Ruby, Nokogiri: Get the element name of the selected node
Extract a specific element from the list of objects
[Technical memo] About the advantages and disadvantages of Ruby
[Ruby] Class nesting, inheritance, and the basics of self
Get the URL of the HTTP redirect destination in Ruby
(Ruby on Rails6) Reflecting the posted content from the form
A record of studying the Spring Framework from scratch
Try using the query attribute of Ruby on Rails
[Ruby On Rails] How to search and save the data of the parent table from the child table
The world of clara-rules (2)
Judgment of the calendar
The world of clara-rules (4)
I will explain the difference between Android application development and iOS application development from the perspective of iOS engineers
The world of clara-rules (1)
The world of clara-rules (3)
definition of ruby method
From Java to Ruby !!
The world of clara-rules (5)
The idea of quicksort
The version of Ruby that was installed by default on the Mac was referenced, not from rbenv
About the [ruby] operator
The idea of jQuery
The story of raising Spring Boot from 1.5 series to 2.1 series part2
Review the basic knowledge of ruby that is often forgotten
Get to the abbreviations from 5 examples of iterating Java lists
Determine that the value is a multiple of 〇 in Ruby