新手问题 新手关于 Ruby 的一个疑问

jhhdoctor · 2015年10月26日 · 最后由 although13 回复于 2015年10月26日 · 1836 次阅读
File.open "/Users/lic/Desktop/3.txt" do |f|

  f.each_line do |line|
    puts line
  end
end

如上代码,我并没有在 File.open 方法中发现 yidle 关键字,为什么可以在这里直接用代码块呢? 见笑了,请大神指点

因为是用 C 写的?你可以试试在命令行运行下面代码 $ gem install pry-doc $ irb require 'pry' binding.pry show-source File#open

https://github.com/pry/pry/wiki/Source-browsing#C_source

#1 楼 @although13 正解。

[3] pry(main)> show-source File#open

From: io.c (C Method):
Owner: Kernel
Visibility: private
Number of lines: 36
static VALUE
rb_f_open(int argc, VALUE *argv)
{
    ID to_open = 0;
    int redirect = FALSE;

    if (argc >= 1) {
        CONST_ID(to_open, "to_open");
        if (rb_respond_to(argv[0], to_open)) {
            redirect = TRUE;
        }
        else {
            VALUE tmp = argv[0];
            FilePathValue(tmp);
            if (NIL_P(tmp)) {
                redirect = TRUE;
            }
            else {
                VALUE cmd = check_pipe_command(tmp);
                if (!NIL_P(cmd)) {
                    argv[0] = cmd;
                    return rb_io_s_popen(argc, argv, rb_cIO);
                }
            }
        }
    }
    if (redirect) {
        VALUE io = rb_funcall2(argv[0], to_open, argc-1, argv+1);

        if (rb_block_given_p()) {
            return rb_ensure(rb_yield, io, io_close, io);
        }
        return io;
    }
    return rb_io_s_open(argc, argv, rb_cFile);
}
需要 登录 后方可回复, 如果你还没有账号请 注册新账号