Day 17 of Dip Advent Calendar :)
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
...!
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
Java
Father.java
//Default package
public class Father {
}
Ruby
father.rb
class Father
end
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
Java
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);
}
}
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
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
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.
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 a
field or a
member variable`.
'
."
is used when expanding expressions.ʻ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;
}
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)
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
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.
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)
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