hakeの日記

Windows環境でプログラミングの勉強をしています。

IronRubyを試してみる

インストールしたのは、こちらの最新版の1.1.3(ruby 1.9.2ベース)

>ir -v
IronRuby 1.1.3.0 on .NET 4.0.30319.225

.NETの作法がまったく分からないので、こちらのソースを参考にさせて頂き、1行目に文字コード指定を追記、ソース内の文字列を日本語にしてみました。
stable(v1.0)版(ruby 1.8.6ベース)では日本語表示が上手くいかない様ですが、v1.1.3では問題なく表示するようですね。


ソース

# coding: Windows-31J
require 'mscorlib'
require 'System.Windows.Forms'
require 'System.Drawing'

class RubyForm < System::Windows::Forms::Form

  def initialize
    self.text = "ウィンドウズフォーム on IronRuby"
    btn = System::Windows::Forms::Button.new
    btn.location = System::Drawing::Point.new(50, 50)
    btn.text = "クリック!"

    btn.click{|sender, e|
      System::Windows::Forms::MessageBox.show("ハロー IronRuby!")
    }
    
    controls.add(btn)
  end

end

System::Windows::Forms::Application.run(RubyForm.new) 
  • ボタン押下処理を独立メソッドにしてみる(こういう書き方で良いのかは不明)
# coding: Windows-31J
require 'mscorlib'
require 'System.Windows.Forms'
require 'System.Drawing'

class RubyForm < System::Windows::Forms::Form

  def initialize
    self.text = "ウィンドウズフォーム on IronRuby"
    @btn = System::Windows::Forms::Button.new
    @btn.location = System::Drawing::Point.new(50, 50)
    @btn.text = "クリック!"
    @btn.click do |sender, e| btn_click(sender, e) end

    controls.add(@btn)
  end

  def btn_click(sender, e)
      p sender.class  # => System::Windows::Forms::Button
      p sender.text.encode('Windows-31J') # => "クリック!"
      p e.class       # => System::Windows::Forms::MouseEventArgs

      System::Windows::Forms::MessageBox.show("ハロー IronRuby!")
  end
end

System::Windows::Forms::Application.run(RubyForm.new)