0

如何将调用者参数的值分配为参数的默认值?我希望该方法将调用者方法Callme#callme的参数值作为默认参数值。nameTheCaller#caller

module Callme
  def callme(hero = name)
    hero
  end
end

class TheCaller
  include Callme 
  def caller(name)
    callme
  end
end

say = TheCaller.new
say.caller("superman")
# => expecting "superman"
4

2 回答 2

2

我知道没有隐含的方法可以做到这一点。你最好的选择是通过 args

class TheCaller
  include Callme
  def caller(*args)
    callme(*args)
  end
end
于 2013-01-31T01:07:20.797 回答
0

也许我不明白这个问题,但是向 TheCaller 添加名称访问器似乎可以按预期工作:

module Callme
  def callme(hero = name)
    hero
  end
end

class TheCaller
  attr_accessor :name
  include Callme 
  def caller(name)
    @name = name
    callme
  end
end

say = TheCaller.new
p say.caller("superman")

# => "superman"
于 2013-01-31T02:00:41.747 回答