如何知道Proc是否是Ruby中的lambda

use*_*991 3 ruby lambda introspection proc

假设我已经创建了一个lambda实例,我想稍后查询这个对象以查看它是proc还是lambda.怎么做到这一点?.class()方法不起作用.

irb(main):001:0> k = lambda{ |x| x.to_i() +1 }
=> #<Proc:0x00002b931948e590@(irb):1>
irb(main):002:0> k.class()
=> Proc
Run Code Online (Sandbox Code Playgroud)

use*_*869 5

Ruby 1.9.3及更高版本

您正在寻找Proc#lambda?方法.

k = lambda { |x| x.to_i + 1 }
k.lambda? #=> true
k = proc { |x| x.to_i + 1 }
k.lambda? #=> false
Run Code Online (Sandbox Code Playgroud)

Pre 1.9.3解决方案

我们将制作ruby原生扩展.创建proc_lambda/proc_lambda.c包含以下内容的文件.

#include <ruby.h>
#include <node.h>
#include <env.h>


/* defined so at eval.c */
#define BLOCK_LAMBDA  2
struct BLOCK {
    NODE *var;
    NODE *body;
    VALUE self;
    struct FRAME frame;
    struct SCOPE *scope;
    VALUE klass;
    NODE *cref;
    int iter;
    int vmode;
    int flags;
    int uniq;
    struct RVarmap *dyna_vars;
    VALUE orig_thread;
    VALUE wrapper;
    VALUE block_obj;
    struct BLOCK *outer;
    struct BLOCK *prev;
};

/* the way of checking if flag is set I took from proc_invoke function at eval.c */
VALUE is_lambda(VALUE self) 
{
    struct BLOCK *data;
    Data_Get_Struct(self, struct BLOCK, data);
    return (data->flags & BLOCK_LAMBDA) ? Qtrue : Qfalse;
}

void Init_proc_lambda() 
{
    /* getting Proc class */
    ID proc_id = rb_intern("Proc");
    VALUE proc = rb_const_get(rb_cObject, proc_id);

    /* extending Proc with lambda? method */
    rb_define_method(proc, "lambda?", is_lambda, 0);
}
Run Code Online (Sandbox Code Playgroud)

创建proc_lambda/extconf.rb文件:

require 'mkmf'
create_makefile('proc_lambda')
Run Code Online (Sandbox Code Playgroud)

在终端cd到proc_lambda并运行

$ ruby extconf.rb
$ make && make install
Run Code Online (Sandbox Code Playgroud)

在irb中测试它

irb(main):001:0> require 'proc_lambda'
=> true
irb(main):002:0> lambda {}.lambda?
=> true
irb(main):003:0> Proc.new {}.lambda?
=> false
Run Code Online (Sandbox Code Playgroud)