テキストの文字数をカウントするスクリプトの1.8と1.9の比較

1.8の場合

% cat /tmp/test.txt|ruby -Ku -e 'p STDIN.read.split(//).size'
92

1.8の場合は日本語を含む場合は-Kuなどとして、
エンコーディングを指定して、
文字数をカウントする場合はsplit(//)とやって正規表現を使って
カウントするというバッドノウハウが必要

1.9の場合

% cat /tmp/test.txt|ruby19 -e 'p STDIN.read.size'          
92

1.9の場合は環境変数LANGを見て、自動的にエンコーディングがセットされるので
test.txtとLANGのエンコーディングが同じ場合は省略。
readした時はこのエンコーディングがセットされる。
String#sizeではバイト数ではなく、文字数が出てくる。

はじめてのswing on jruby その壱


ボタンを押せるけど、何も反応しないプログラム。
Hello Worldだと思っておけ。)
Javaで書くと

import javax.swing.*;

public class SimpleGui1 {
  public static void main (String [] args) {
    JFrame frame = new JFrame();
    JButton button = new JButton("click me");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(button);
    frame.setSize(300,300);
    frame.setVisible(true);
  }
}

Jrubyで書くと

#!/usr/bin/env jruby
require 'java'
include_class 'javax.swing.JFrame'
include_class 'javax.swing.JButton'

class SimpleGui1
  def initialize
    frame=JFrame.new
    button=JButton.new("click me")
    frame.default_close_operation=(JFrame::EXIT_ON_CLOSE)
    frame.content_pane.add(button)
    frame.setSize(300,300)
    frame.visible=(true)
  end
end

SimpleGui1.new

ポイント

  • swingはJavaの機能なのでrequire 'java'を書く
    • これを書かないとinclude_classがそもそも使えない
  • 必要なswingのクラスをinclude_classで読み込み。Javaでいうimportと一緒。
  • メソッド名はsetDefaultCloseOperationがdefault_close_operation=と言った感じにRuby流の名前で呼び出せる。
    • これはRubyのセッターとゲッターの一般的なネーミングルール
    • ただし、#size=のように使えないものもある。この場合はsetSize(300,300)のようにJava流に使うべし

はじめてのswing on jruby その弐

import javax.swing.*;
import java.awt.event.*;

public class SimpleGui1B implements ActionListener {
  JButton button;

  public static void main (String [] args) {
    SimpleGui1B gui = new SimpleGui1B();
    gui.go();
  }
  public void go() {
    JFrame frame = new JFrame();
    button = new JButton("click me");
    button.addActionListener(this);
    frame.getContentPane().add(button);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300,300);
    frame.setVisible(true);
  }
  public void actionPerformed(ActionEvent event){
    button.setText("I've been clicked!");
  }
}

clickされたときにボタンの文字が入れ替わるようになっているものです。
これをjrubyで書くと

#!/usr/bin/env jruby
require 'java'
include_class 'javax.swing.JFrame'
include_class 'javax.swing.JButton'
include_class 'java.awt.event.ActionListener'

class SimpleGui1B
  include java.awt.event.ActionListener
  def initialize
    frame=JFrame.new
    @button=JButton.new("click me")
    @button.add_action_listener(self)
    frame.default_close_operation=(JFrame::EXIT_ON_CLOSE)
    frame.content_pane.add(@button)
    frame.setSize(300,300)
    frame.visible=true
  end
  def actionPerformed(event)
    @button.text="I've been clicked!"
  end
end

SimpleGui1B.new

イベントが発生した時はイベントの処理のインスタンスを与えなければならないのですが、
これはselfでもいけました。
上のjavaのサンプルもthisって書いてあるので、真似をしてselfと書いたら
これでOKでした。後はメソッドを定義して、buttonをインスタンス変数@buttonに変更し、
実行したらいけました。
implementsしている部分はRubyのmix-inでOKですね。

からJavaのサンプルは引用しました。