LoginSignup
6
1

More than 5 years have passed since last update.

Rubyのスクリプトに文法エラーがあるかどうかを調べる

Posted at

rubyには起動オプションで -c という文法エラーの有無をチェックするものがあります。

実行して文法エラーが存在しない場合は Syntax OK が出力されます。

hello.rb
puts "hello world"
$ ruby -c hello.rb
Syntax OK

文法エラーを含んでいる場合はそのエラーが出力されます。

hello.rb
puts "hello world'
$ ruby -c hello.rb
hello.rb:1: unterminated string meets end of file

このオプションは .rb ファイル以外にも使用が可能で、例えば下記のCのコードに対して実行してみると Syntax OK が出力されます。

hello.c
#include <stdio.h>

int main () {
  printf("hello world!\n");
  return 0;
}
$ruby -c hello.c                                                                                                                                             
Syntax OK

試しに動くように書いてみました。

c.rb
class C
  def self.run(&block)
    new.instance_eval &block
  end

  def int(val)
  end

  def main
    yield
  rescue LocalJumpError => ex
  end

  def printf(str, *values)
    puts str % values
  end
end

C.run do
  #include <stdio.h>

  int main() {
    printf("hello world\n");
    return 0;
  }
end

出力

hello world

ちょっと無理矢理感がありますが、動かすことができました。

参考サイト

Rubyの起動

6
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1