Ruby

Java VS Ruby The Third Impact

Javaで書く基本ループ

public class SampleC {

public static void main(String[] args) {
int i = 0, j = 0;
while(true){
if(i >= 5) break;
System.out.print(” ” + i++);
}
System.out.print(“:”);
do{
System.out.print(” ” + j);
j++;
} while(j < 5);
System.out.println();
for(int m = 0, n = 20; m < n; m += 5,n++){
if(m % 2 == 0) continue;
System.out.println(“m = ” + m + ” n = ” + n);
}

}

}

rubyで書く基本ループ

class SampleC
def main
i = j = 0
while true
break if i >= 5
p (” ” + i.to_s)
i += 1
end
p “:”
loop do
p (” ” + j.to_s)
j += 1
break if j < 5
end
p “\n”
m = 0
n = 20
for s in 1..4
m += 5
n += 1
next if m % 2 == 0
p (“m = ” + m.to_s + ” n = ” + n.to_s + “\n”)
end
end
end
x = SampleC.new
x.main

ちなみにRubyは実行環境入れてないのでエラーチェックしてないです。

追記:

チェックしたところ、ダブルクォーテーションが全角なのを除いて

コピペでちゃんと動きました。

Java VS Ruby Returns

JAVAの教科書にあったソース

class Dog {
 int weight = 50;
 static {
  System.out.println(“static inr”);
 }
 {
  System.out.print(“inr “);
 }
 Dog() {
  System.out.println(“ctr”);
 }
 void meth() {
  System.out.println(weight);
 }

}

class SampleA {
 public static void main(String[] args){
  Dog x = new Dog();
  Dog y = new Dog();
  x.meth();
 }
}

Rubyに翻訳

class Dog
 def initialize
  @weight = 50
  p “inr ctr”
 end
 def meth
  p @weight
 end
end

p “static inr”
x = Dog.new
y = Dog.new
x.meth

 もういっちょJAVA

import java.util.*;

class SampleB {
 public static void main(String[] args){
  int[] ds = {1, 2, 3, 4, 5};
  for(int d : ds)
   System.out.println(d);
  System.out.println();
  int[][] nns = {{1, 2, 3}, {10, 20, 30}, {100, 200, 300}};
  for(int[] ns : nns){
   for(int n : ns){
    System.out.println(n);
   }
   System.out.println();
  }
  List<String> ss = new ArrayList<String>();
  ss.add(“abc”);
  ss.add(“def”);
  ss.add(“ghi”);
  for(String s : ss)
   System.out.println(s);
  
 }
}

もういっちょRuby

class SampleB
 def main
  ds = [1, 2, 3, 4, 5]
  for d in ds
   p d
  end
  p “”
  nns = [[1, 2, 3], [10, 20, 30], [100, 200, 300]]
  for ns in nns
   for n in ns
    p n
   end
   p “”
  end
  ss = []
  ss.push(“abc”)
  ss.push(“def”)
  ss.push(“ghi”)
  for s in ss
   p s
  end
 end
end

x = SampleB.new
x.main

Java VS Ruby

Javaで書くif

int foo = 0, bar;
if(foo == 0){
 bar = 10;
}

Rubyで書くif

foo = 0
if foo == 0
 bar = 10
end

Javaで書くfor

for(int i = 0, i < 10, i++){
 System.out.println(i);
}

Rubyで書くfor

for i in 0…10
 print i
end

Javaで書くクラスとメソッド

public class foo extends bar {
 public void main(String[] args) {
  do_something();
 }
 public int do_something() {
  return 0;
 }
}

Rubyで書くクラスとメソッド

class foo < bar
 def main
  do_something
 end
 def do_something
  return 0
 end
end

Javaで書くアクセサ

private foo;
private bar;
private baz;
public String getFoo()
{
 return foo;
}
public void setFoo(String foo)
{
 this.foo = foo;
}
public String getBar()
{
 return bar;
}
public void setBaz(String baz)
{
 this.baz = baz;
}

Rubyで書くアクセサ

attr_accessor:foo
attr_reader:bar
attr_writer:baz