Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby assign context to lambda?

Tags:

ruby

lambda

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_accessor :name

  def init_rule 
    @name = "ruby"
    Rule.new.get_rule.call() # should say "ruby" but say what object of class Rull, does not have variable name
    # or self.instance_eval &Rule.new.get_rule
  end
end

My target is -> stored procedure objects without contexts, and assign context before call in specific places. Is it possible?

like image 458
vorobey Avatar asked Sep 19 '11 11:09

vorobey


2 Answers

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
like image 168
forforf Avatar answered Oct 11 '22 11:10

forforf


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
like image 37
Joshua Cheek Avatar answered Oct 11 '22 11:10

Joshua Cheek