Ruby assign context to lambda?

后端 未结 3 996
眼角桃花
眼角桃花 2021-01-12 23:13

Is it possible not to assign context to lambda?

For example:

class Rule
  def get_rule
    return lambda {puts name}
  end
end

class Person
  attr_         


        
3条回答
  •  悲&欢浪女
    2021-01-12 23:28

    Yeah, but be careful with it, this one is really easy to abuse. I would personally be apprehensive of code like this.

    class Rule
      def get_rule
        Proc.new { puts name }
      end
    end
    
    class Person
      attr_accessor :name
    
      def init_rule 
        @name = "ruby"
        instance_eval(&Rule.new.get_rule)
      end
    end
    

提交回复
热议问题