人気ブログランキング | 話題のタグを見る

スニペット活用環境 srb

スニペットを活用するための、対話型 Ruby 環境のスニペット srb を作った。

edb や minirb などの機能を集めて贅肉を落としただけのもの。使い方はほぼ以前の記事と同じ。コードサイズが小さいので邪魔にならない。

使用例

Ruby$ ruby srb.rb
srb> a = SRB.edit
"puts \"hello, world\"\n"
srb> puts a
puts "hello, world"
nil
srb> eval a
hello, world
nil
srb> a = SRB.edit( a )
"total = 0\nfor i in 1..10\n total += i\nend\nputs total\n"
srb> puts a
total = 0
for i in 1..10
  total += i
end
puts total
nil
srb> eval a
55
nil
srb> SRB.save('total.rb', a)
53
srb> b = SRB.load('total.rb')
"total = 0\nfor i in 1..10\n total += i\nend\nputs total\n"
srb> eval b
55
nil

ファイル名: srb.rb (eval,open は半角英数に変換して使用)

require 'readline'
include Readline

module SRB
  def SRB.edit(prog = nil)
    if prog != nil
      File.open('temp.txt','w') {|f| f.write(prog)}
    end
    system "vi temp.txt"
    prog = IO.read('temp.txt')
    system "rm temp.txt"
    prog
  end
  
  def SRB.save(path, var)
    File.open(path, 'w') {|f| f.write(var)}
  end

  def SRB.load(path)
    IO.read(path)
  end
end

loop do
  begin
    _line = readline('srb> ', true)
    p eval(_line, TOPLEVEL_BINDING)
  rescue SyntaxError, LoadError, StandardError
    STDERR.puts "Warning: #$!"
  end
end

入力行の値を表示させたくない場合は、p eval(line, TOPLEVEL_BINDING) の p を消す。Windows で使う場合は、SRB.edit の vi を適当なエディタに、また、rm を del に置き換える。
by tnomura9 | 2008-09-24 01:44 | Ruby | Comments(0)
<< Ruby 標準ライブラリの歩き... 車輪を二度発明しないためには >>