Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 从复杂方法链中获取父实例化对象?_Ruby_Class_Object - Fatal编程技术网

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

Ruby 从复杂方法链中获取父实例化对象?,ruby,class,object,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.add.ketchup('tons!)时,是否仍然

原谅这个做作的例子,如果我有

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

class OverpricedStadiumSnack
  def add
    Condiment.new
  end
end

hotdog = OverpricedStadiumSnack.new
。。。调用
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)
。。。但我希望能够做到这一点,而不必显式地传递热狗。

可能是:

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)

谢谢现在似乎很明显