Java engineers now compare to learn the basic grammar of Ruby Part 1 (Basic, Variables)

Introduction

I think that if you learn a language with a different idea, it will be quicker to learn by difference, so before you start Rails, let's redo the basic grammar. It is an easy idea to remember by creating something like a cheat sheet.

I think there are various shortages, but please understand that I am only doing what I think is necessary for the time being. Since I often write, I will divide the article.

Tsukkomi is welcome.

environment

paiza.io It is easier to execute in such a case

The version when this was made is as follows. You can check the version from Help.

Ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-linux] Java openjdk version "12" 2019-03-19

comment

How to write a comment

//For one line

/*
For multiple lines
*/
#For one line

=begin
For multiple lines
=end

__END__
Everything after this line will be a comment

Processing delimiter

It's about the delimiter when you run it.

String str = "World"; //Processing is separated only by a semicolon
tmp1 = 1 #Basically, line breaks are separated
tmp2 = 2;print("#{tmp1 + tmp2}") #Semicolon is also valid as a delimiter

Standard output

Hello World First from Hello World. Java has a lot of types because you have to create classes. Since Ruby can write processing suddenly, the amount of typing is small.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

#There seem to be several names, so please refer to the following
# https://qiita.com/naoge/items/f5d84581d3a301a9c22f
print("Hello World")

Variable expansion

You will often see variables. In Java, it is expanded by declaring a format specifier with the printf method and setting a variable. Variable expansion can be used in Ruby, so I will do it.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String str = "World";
        // System.out.println("Hello" + str)But it is possible.
        System.out.printf("Hello %s", str);
    }
}

str = "World";
print("Hello #{str}") #{formula(variable)}でvariable展開可能

Variable definition

We've used a few variables above, but here's a description of them. Since Ruby variables are a little complicated, it seems to be troublesome to deal with scope here, so I have not seen it. Due to that influence, I think that it is not possible to cover all the variables of Ruby.

Local variables

Java is a statically typed language, so you need to declare what type the variable is. Since Ruby is a dynamically typed language, you don't need to specify any type. As a rule of Ruby, identifiers starting with lowercase letters or underscores are local variables. It seems that underscores are for variables that are not used, so be careful about that.

String tmp1 = "1";
tmp1 = "1"

Ruby allows variables of different types to be included in variables once declared.

tmp1 = 1

puts("#{tmp1}") #puts is standard output with line breaks

tmp1 = "2"

puts("#{tmp1}")

constant

Java declares with final to prevent rewriting. Generally, it's okay to add static, so add static as well. Since Ruby defines variables that start with English capital letters as constants, it is judged only by the variable name.

public static final String ONE = "1";
ONE = "1"

__END__
If you rewrite this variable, the following warning will occur and the program will not work.

warning: already initialized constant ONE

Unlike Java, Ruby constants can be defined at the top level as well. And a constant with the same name can be created in the class. In that case, the priority will decrease as you go from the place of use to the outside.

ONE = "1"

class A
   ONE = "2"
   
   def print
       p ONE
   end
end

a = A.new
a.print #This is displayed as 2

p ONE #This is displayed as 1

Global variables

Java does not have global variables in the strict sense. Since everything needs to belong to Ojbect, you can create variables that look like the whole, but they are not global variables.

Ruby can be declared as a global variable by prefixing it with $. You can also refer to undeclared global variables, but they will be nil.

$str = "a"

Instance variables

From here on, the complexity of Ruby variables comes out. I understand that instance variables are similar to member variables in Java. Recognition that it is treated in the same way as protected in terms of scope!

Ruby declares variables with @ at the beginning. Unlike Java, it is not declared as a member variable and the reference range is wide (if it is a class instance variable), so if you complicate the class, you will not know where something is happening, so I feel careful. I think it's the right way to keep the class simple instead of not using it, so be careful there.

Also, in the case of Ruby, the reference of the class method (self) and the instance method (without self) are different. Since self feels like a static method, I'm trying to understand that.

public class A {
    protected String str;
}
class A
  def save(target)
    @str = target;
  end
end

Class variables

A variable that belongs to a class. It seems to be treated as static in Java, and it affects other class instances.

It's safer not to use this. It only seems to be the cause of chaos.

public class A {
    protected static String str;
}
class A
  def save(target)
    @@str = target;
  end
end

Class instance variable

If you declare an instance variable to belong to a class, it becomes a class instance variable and can be referenced only from the class method (self). The difference with instance variables seems to be that they are scoped only from their class methods. If you try to see it from another, it will be treated as an instance variable.

It seems that this is not possible with Java, so it seems that you have to remember that you can also do this.

# Your code here!
class A

  def save(user_name)
    @str = user_name
  end
    
  def self.save(user_name)
      @str = user_name
  end

  def self.print
    p @str
  end

  def print
    p @str
  end
end

a = A.new
a.save("aaa")
a.print

A.save("bbb")
A.print

Recommended Posts

Java engineers now compare to learn the basic grammar of Ruby Part 1 (Basic, Variables)
Java engineers now compare to learn the basic grammar of Ruby Part 2 (classes, methods)
I tried to summarize the basic grammar of Ruby briefly
Review of Ruby basic grammar
Be sure to compare the result of Java compareTo with 0
Java to learn with ramen [Part 1]
Basic usage of java Optional Part 1
[Basic knowledge of Java] Scope of variables
[Ruby] Display the contents of variables
Connecting to a database with Java (Part 1) Maybe the basic method
Introduction to Ruby basic grammar with yakiniku
part of the syntax of ruby ​​on rails
Compare the elements of an array (Java)
[Java] I personally summarized the basic grammar.
Output of the book "Introduction to Java"
I translated the grammar of R and Java [Updated from time to time]
[Ruby on Rails] How to make the link destination part of the specified id
[Promotion of Ruby comprehension (1)] When switching from Java to Ruby, first understand the difference.
I tried to compare the infrastructure technology of engineers these days with cooking.
How to find the cause of the Ruby error
[Ruby] Basic knowledge of class instance variables, etc.
The story of introducing Ajax communication to ruby
[Java] The confusing part of String and StringBuilder
[Ruby] Code to display the day of the week
[Java] How to get the authority of the folder
Java Welcome to the Swamp of 2D Arrays
Java basic grammar
Java basic grammar
Java basic grammar
Java basic grammar
# 4 Started Ruby "Fun Ruby 6th Edition" Part 2 Learn the basics Chapter 4 Objects and variables / constants
The part I was addicted to in "Introduction to Ajax in Java Web Applications" of NetBeans
[Java] How to get the URL of the transition source
[Java] Basic summary of Java not covered by Progate ~ Part 1 ~
How to write Scala from the perspective of Java
[Ruby] How to find the sum of each digit
[Java] How to get the maximum value of HashMap
Java review ① (development steps, basic grammar, variables, data types)
Memorandum (Ruby: Basic grammar: Use by naming the process)
Introduction to Java for beginners Basic knowledge of Java language ①
Java: Use Stream to sort the contents of the collection
~ I tried to learn functional programming in Java now ~
What Java engineers need to prepare for the Java 11 release
I want to be aware of the contents of variables!
Replace only part of the URL host with java
From Java to Ruby !!
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
I tried to summarize the basics of kotlin and java
Get to the abbreviations from 5 examples of iterating Java lists
20190803_Java & k8s on Azure The story of going to the festival
I want to expand the clickable part of the link_to method
Command to check the number and status of Java threads
Comparison of how to write Callback function (Java, JavaScript, Ruby)
I want to use the Java 8 DateTime API slowly (now)
[Java] To know the type information of type parameters at runtime
[Java] Basic summary of Java not covered by Progate ~ Part 2 · List ~
[Ruby] How to retrieve the contents of a double hash
How to derive the last day of the month in Java
Road to Java Engineer Part2 What kind of language is Java?
The story of pushing Java to Heroku using the BitBucket pipeline