Getting Started with Ruby for Java Engineers

Day 17 of Dip Advent Calendar :)

Introduction

What kind of article?

Java engineers started writing Ruby, This is an article that shares what I thought, "** Is this something like Java's ◯◯! **".

This time I will write about coding ...!

table of contents

Class Instantiate (#instantiate) [Method](# method) [Instantiation (with arguments)](# Instanceization (with arguments)) Array / List (# Array List) [Map / hash](#map hash) [What was useful to know](# What was useful to know) Conclusion

class

Java

Father.java


//Default package
public class Father {
}

Ruby

father.rb


class Father
end

Instantiation

Java

Main.java


//Default package
public class Main {

    public static void main(String[] args) {
        Father father = new Father(); 
    }

}

Ruby

main.rb


require './father.rb' # ./father.Read rb. Similar to import in java.

father = Father.new

Method

Java

Declaration

Father.java


public class Father {

    //static method
    public static void hello() {
        System.out.println("Hello...");
    }

    //Non-static method (instance method)
    public void tellTheTruth() {
        System.out.println("I am your father.");
    }

    //Non-static method (instance method):With arguments
    public void fuga(String words) {
        System.out.println(words);
    }

}

call

Main.java


public class Main {

    public static void main(String[] args) {
        Father.hello(); // Hello...
        Father father = new Father(); 
        father.tellTheTruth(); // I am your father.
        father.fuga("Nooo!!"); // Nooo!!
    }

}

Ruby

Declaration

father.rb


class Father
  #Class method
  def self.hello
    puts 'Hello...'
  end

  #Instance method (no arguments)
  # snake_case notation
  def tell_the_truth
    puts 'I am your father.'
  end

  #Instance method (with arguments)
  def fuga(words)
    puts words
  end
end

call

main.rb


require './father.rb'

Father.hello # hoge

father = Father.new

father.tell_the_truth() # I am your father.
father.tell_the_truth   # I am your father. ()Can be omitted. It looks like a member call, but it's a method call.

father.fuga('nooooo!!') # nooooo!!
father.fuga 'nooooo!!'  # nooooo!! ()Can be omitted. It is often used, but it is difficult to understand on the right side of the method, so it is better to avoid it.

Instantiation (with arguments)

In the above instantiation, it was a constructor without arguments, but this time we will make it more object-like with a constructor with arguments. Java

Father.java


public class Father {

    private String name;

    public Father(String name) {
        this.name = name;
    }

    public void tellTheTruth() {
        System.out.println("I am " + name + "...");
    }

}

Ruby

father.rb


class Father
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def tell_the_truth
    puts "I am #{name}..."
  end
end

ʻInitializeis the so-called constructor. Also,@ hogerepresents an instance variable. In Java, it's often called afield or a member variable`.

About character strings

attr_accessor / About accessors

ʻAttr_accessor `defines an accessor (so-called getter / setter). In fact, it's the same as writing the following code.

def name
  @name 
end

def name=(val)
  @name = val
end

Same as Java below.

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

Array / list

Java

Main.java


package com.company;

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("pen", "pineapple", "apple", "pen");

        // java5-7
        for (String word : words) {
            System.out.println(word);
        }
        //java8 or later
        words.forEach(System.out::println);
    }
}

Ruby

ppap.rb


words = ['pen', 'pineapple', 'apple', 'pen']

puts words[0] # pen

words.each do |word|
  #The following processing is executed in a loop.
  #A looped object is stored in word.
  #So the first loop is'pen'Is displayed on the console.
  puts word
end

Arrays are represented by the Array class. Array --Ruby Reference

#Each is often used for array iterations. There is also a for statement, but most loops will be fine if you remember #each first.

The following article is very easy to understand about the block represented by do to ʻend`.

Understanding how to use [Ruby] blocks and Proc (It can be confusing, so it may be better to stock it and read it later.)

Also, if you keep in mind that the array of character strings is generated by the following writing method, You will be less likely to be thrilled to read code written by others.

#Generate an array of strings
words = %w(pen pineapple apple pen)

Use% notation (percentage notation) in Ruby is very helpful in this area. (Stock recommended)

Map / hash

Java

Main.java


import java.util.HashMap;
import java.util.Map;

public class Main {

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();

        map.put("name", "Dip");
        map.put("service", "Cod roe in a nurse");

        System.out.println(map.get("name")); //Dip
        System.out.println(map.get("service")); //Cod roe in a nurse
    }

}

Ruby There are several ways to write hashes in Ruby.

main.rb


#1 Use a character string as a key
dip = {'name' => 'Dip', 'service' => 'Cod roe in a nurse'}

puts dip['name'] #Dip
puts dip['service'] #Cod roe in a nurse

#2 Use the symbol as a key.
dip = {name: 'Dip', service: 'Cod roe in a nurse'}

puts dip[:name] #Dip
puts dip[:service] #Cod roe in a nurse

The writing method is not limited to the above, and the support differs depending on the version. The following articles are very easy to understand and should be read. Various hash declaration methods for Ruby

What was useful to know

About namespaces (about Foo :: Bar.new)

You may be confused by the following writing style.

Foo::Bar.new

This is the process that actually instantiates the following classes.

module Foo
  class Bar
  end
end

One of the roles of module is to provide ** namespace **. (Other functions such as providing methods.) It's a concept similar to a package in Java.

Bar.java


package foo;

public class Bar {
}

Fuga.java


package hoge;

import foo.Bar;

public class Fuga {
    Bar bar = new Bar();
}

Similar to the above.

NoMethodError occurs instead of NullPointerException

Ruby's nil is similar to Java's null, but a little different.

nil is the only instance of the NilClass class. nil represents false with the false object, and all other objects are true. class NilClass (Ruby 2.3.0)

Therefore, when you call a method that does not exist in the nil class, You will get an exception called NoMethodError instead of an exception like NullPointerException.

main.rb


#Call an undefined method.
nil.special_method 
#Special for Nil Class_Since there is no method, the following error is output.
undefined method `special_method' for nil:NilClass (NoMethodError)

in conclusion

I personally think that Ruby has a beautiful grammar, convenient built-in classes, and the more you use it, the more familiar you are with it. If you enter from Java, you may get something like "** I'm worried about something without a type declaration !! **", but I think you'll soon get used to it. (I got used to it in 3 days.) When you start another language, your view of the original language will change, so why not start it?

Recommended Posts

Getting Started with Ruby for Java Engineers
Getting Started with Ruby
Getting Started with Java Collection
Links & memos for getting started with Java (for myself)
Getting Started with Java Basics
Getting Started with Ruby Modules
Getting Started with Legacy Java Engineers (Stream + Lambda Expression)
Getting started with Java lambda expressions
Getting Started with Docker for Mac (Installation)
Getting Started with Java Starting from 0 Part 1
Getting Started with DBUnit
Getting Started with Swift
Getting Started with Docker
Getting Started with Doma-Transactions
Getting Started with Java 1 Putting together similar things
Getting started with Kotlin to send to Java developers
Getting Started with Doma-Annotation Processing
Getting started with Java programs using Visual Studio Code
Java programming exercises for newcomers unpopular with active engineers
Getting Started with JSP & Servlet
Getting Started with Spring Boot
Getting started with Java and creating an AsciiDoc editor with JavaFX
Getting Started with Java_Chapter 5_Practice Exercises 5_4
Ruby convenience methods for fledgling engineers
Enable OpenCV with java8. (For myself)
[Google Cloud] Getting Started with Docker
Getting Started with Docker with VS Code
Returning to the beginning, getting started with Java ② Control statements, loop statements
Getting Started with Doma-Criteria API Cheat Sheet
Learn Java with "So What" [For beginners]
Getting Started with Parameterization Testing in JUnit
Getting Started with Ratpack (4)-Routing & Static Content
Getting started with the JVM's GC mechanism
Interoperability tips with Kotlin for Java developers
Getting Started with Language Server Protocol with LSP4J
Getting Started with Creating Resource Bundles with ListResoueceBundle
Getting Started with Machine Learning with Spark "Price Estimate" # 1 Loading Datasets with Apache Spark (Java)
Getting Started with Java_Chapter 8_About Instances and Classes
[Java] How to test for null with JUnit
Ask for n business days later with JAVA
For JAVA learning (2018-03-16-01)
I started Ruby
Getting Started with Doma-Using Projection with the Criteira API
Simple obstacle racing made with processing for Java
Procedure for operating google spreadsheet with API (ruby)
Try to link Ruby and Java with Dapr
For my son who started studying Java with "Introduction to Java" in one hand
Getting Started with Doma-Using Subqueries with the Criteria API
2017 IDE for Java
Getting Started with Doma-Using Joins with the Criteira API
[Rails] Procedure for linking databases with Ruby On Rails
For Java engineers starting Kotlin from now on
Docker Container Operations with Docker-Client API for Java
Getting Started with Doma-Introduction to the Criteria API
An introduction to Groovy for tedious Java engineers
Java for statement
I tried Getting Started with Gradle on Heroku
Going back to the beginning and getting started with Java ① Data types and access modifiers
Workaround for Bundler.require error when executing ruby with crontab
Solving with Ruby and Java AtCoder ABC129 D 2D array
Solving with Ruby, Perl and Java AtCoder ABC 128 C