1

Theinner_method只会在 内部调用outer_method,并且它的参数将始终与outer_method's 相同。

这有效:

def outer_method(word)
  inner_method(word)
  puts word + " are like candy."
end

def inner_method(same_word)
  puts "I really love " + same_word + "!"
end

outer_method("onions")

但这不是:

def outer_method(word)
  inner_method
  puts word + "tastes like candy."
end

def inner_method
  puts "I really love " + word + "!"
end

outer_method("onions")

似乎对inner_method的引用word没有被outer_method. 有一个更好的方法吗?

(我意识到在上面的例子中没有理由分开inner_method;为了清楚起见,这被简化了)

4

2 回答 2

1

老实说,我认为你的第一个技术是最好的方法,而且非常地道。不过,这里还有另一种选择:

def outer_method(word)
  inner_lambda = lambda do
    puts "I really love " + word + "!"
  end

  inner_lambda.call
  puts word + " tastes like candy."
end

outer_method("onions")

lambda创建一个词法闭包,这意味着它捕获周围环境,包括对word.

于 2013-06-26T07:12:13.980 回答
1

There are two concerns with your question. The shallow one is your learning Ruby syntax. The deeper one is learning proper coding patterns. In your case, word object begs to exist:

class MyWord < String
  def singular?; @singular end

  def initialize **setup
    singular, plural = setup[:singular], setup[:plural]
    if singular then @singular = true
      super singular
    elsif plural then @singular = false
      super plural
    else fail ArgumentError, "Bad MyWord constructor arguments!" end
  end

  def interjection_1
    "I really love #{self}!"
  end

  def interjection_2
    "#{capitalize} #{singular? ? 'is' : 'are'} like cand#{singular? ? 'y' : 'ies'}!"
  end

  def hysteria
    puts interjection_1
    puts interjection_2
  end
end

And then:

MyWord.new( plural: "onions" ).hysteria
于 2013-06-26T07:59:08.040 回答