从复杂的方法链中获取父实例化对象?

时间:2012-07-29 06:40:42

标签: ruby class object

原谅人为的例子,如果我有......

class Condiment
  def ketchup(quantity)
    puts "adding #{quantity} of ketchup!"
  end
end

class OverpricedStadiumSnack
  def add
    Condiment.new
  end
end

hotdog = OverpricedStadiumSnack.new

...无论如何,在调用hotdog时,可以从Condiment#ketchup内访问hotdog.add.ketchup('tons!')实例化对象吗?


到目前为止,我发现的唯一解决方案是明确地传递hotdog,如下所示:

class Condiment
  def ketchup(quantity, snack)
    puts "adding #{quantity} of ketchup to your #{snack.type}!"
  end
end

class OverpricedStadiumSnack
  attr_accessor :type

  def add
    Condiment.new
  end
end

hotdog = OverpricedStadiumSnack.new
hotdog.type = 'hotdog'

# call with
hotdog.add.ketchup('tons!', hotdog)

...但我希望能够在不明确传递hotdog的情况下做到这一点。

1 个答案:

答案 0 :(得分:2)

可能是:

class Condiment
  def initialize(snack)
    @snack = snack
  end

  def ketchup(quantity)
    puts "adding #{quantity} of ketchup! to your #{@snack.type}"
  end
end

class OverpricedStadiumSnack
  attr_accessor :type

  def add
    Condiment.new(self)
  end
end

hotdog = OverpricedStadiumSnack.new
hotdog.type = 'hotdog'
hotdog.add.ketchup(1)