【问题标题】:Calling functions inside functions when the inner function's arguments will always be the same as the outer's当内部函数的参数始终与外部函数的参数相同时,在函数内部调用函数
【发布时间】:2013-06-23 05:02:38
【问题描述】:

inner_method 只在outer_method 内被调用,其参数将始终与outer_method 相同。

这行得通:

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_methodword 的引用似乎没有被outer_method 注册。有没有更好的方法来做到这一点?

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

【问题讨论】:

    标签: ruby function methods


    【解决方案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 的引用。

    【讨论】:

    • 啊,谢谢。我还不是很喜欢 lambdas。不过,我将只保留第一种技术,因为它的效率实际上并没有降低多少。
    【解决方案2】:

    您的问题有两个问题。浅层是你学习 Ruby 语法。更深层次的是学习正确的编码模式。在你的情况下, word 对象乞求存在:

    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
    

    然后:

    MyWord.new( plural: "onions" ).hysteria
    

    【讨论】:

    • 感谢您的反馈。我已经删除了我的帖子。
    • 感谢您提供的信息。我的语法有什么问题?另外,你能推荐一本涵盖“正确编码模式”的书或网站吗?
    • @user2493615:模式dates back to before Ruby。它一半是科学,一半是艺术。 Matz 本人在很大程度上是根据直觉设计 Ruby,所以如果您在使用它时也这样做,请不要感到羞耻。我也不是理论家,但我可以告诉你,如果在各种方法的参数中不断出现相同的问题,那么是时候为该问题创建一个类并将这些方法作为实例方法了。也许this great talk 也影响了我。
    猜你喜欢
    • 1970-01-01
    • 2018-10-21
    • 2018-06-12
    • 2021-09-21
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    相关资源
    最近更新 更多