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

How can one know if a Proc is a lambda or not in Ruby

假设我创建了一个 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

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

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);
}

创建proc_lambda/extconf.rb文件:

require 'mkmf'
create_makefile('proc_lambda')

在终端 cd 到 proc_lambda 和 运行

$ ruby extconf.rb
$ make && make install

在 irb 中测试它

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