Ruby assign context to lambda?

后端 未结 3 1029
眼角桃花
眼角桃花 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:29

    A bit late to party, but here's an alternate way of doing this by explicitly passing the context to the rule.

    class Rule
      def get_rule
        return lambda{|context| puts context.name}
      end
    end
    
    class Person
      attr_accessor :name
      def init_rule
        @name = "ruby"
        Rule.new.get_rule.call(self)
      end
    end
    
    Person.new.init_rule
    #=> ruby
    

提交回复
热议问题