Ruby assign context to lambda?

后端 未结 3 1019
眼角桃花
眼角桃花 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条回答
  •  Happy的楠姐
    2021-01-12 23:49

    In the spirit of being really late to the party ;-)

    I think the pattern that you are using here is the Strategy pattern. This separates the concerns between the code that changes "rules" and the part that is re-used "person". The other strength of this pattern is that you can change the rules at run-time.

    How it could look

    class Person
      attr_accessor :name
    
      def initialize(&rules)
        @name = "ruby"
        instance_eval(&rules)
      end
    end
    
    Person.new do 
      puts @name
    end
    
    => ruby
    

提交回复
热议问题