匿名模块可以用于什么目的? [英] What purpose can anonymous modules serve?

查看:26
本文介绍了匿名模块可以用于什么目的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 应用程序中的匿名模块有什么用途?这个概念本身很容易理解,但我无法想象你会使用这样的东西的任何理由.他们解决了什么问题?

What purpose could anonymous modules in a Ruby app serve? The concept itself is easy to grasp, but I can't imagine any reason that you'd ever use such a thing. What problem do they solve?

推荐答案

这里有一个更通用的原则.

There is a more general principle at work here.

Phil Karlton 有句名言:计算机科学只有两个难题:缓存失效和命名事物." 所以,给事物命名是很困难的.这意味着如果我们可以避免命名一个东西,我们应该这样做!

Phil Karlton famously said: "There are only two hard problems computer science: cache invalidation and naming things." So, naming things is hard. Which means that if we can get away with not naming a thing, we should do it!

或者,如果您从不同的角度看待它:如果给事物命名很困难,那么给事物命名就意味着该事物很重要.但有时,我们的程序中有些东西不重要,因此不值得一提.

Or, if you look at it from a different perspective: if naming things is hard, then giving something a name means that thing is important. But sometimes, there are things in our programs which aren't important and thus aren't worthy of a name.

这不是 Ruby 模块独有的.你可以问关于任何匿名概念的问题,事实上,这个问题确实一直被问到.当 C# 2.0 引入匿名方法时,人们会问为什么要使用没有名称的方法,当 C# 3.0 引入匿名 lambda(和匿名类型)时,人们会问为什么要使用它们.与 Python 的命名函数相比,Python 的匿名函数受到严格限制,Python 社区询问为什么人们需要成熟的匿名函数.当然,作为 Ruby 程序员,我们习惯于轻量级(块)和完全具体化(Procs)匿名函数,我们无法理解为什么永远想用一个.

This is not unique to Ruby modules. You could ask the question about any anonymous concept, and in fact, the question does get asked all the time. When C# 2.0 introduced anonymous methods, people asked why one would ever want to use a method without a name, when C# 3.0 introduced anonymous lambdas (and anonymous types), people asked why one would ever want to use them. Python's anonymous functions are severely restricted compared to Python's named functions, and the Python community asks why one would ever need full-blown anonymous functions. Of course, we, as Ruby programmers are so used to lightweight (blocks) and fully reified (Procs) anonymous functions that we can't understand why one would ever not want to use one.

Java 从 1.1 开始就有匿名类,从 8 开始就有匿名 lambda.基本上,匿名事物"无处不在,它们很有用,特别是对于快速一次性使用.

Java has anonymous classes since 1.1 and anonymous lambdas since 8. Basically, anonymous "things" are everywhere and they are useful, especially for quick one-off usage.

例如,如果您只想包装一些现有的方法,而不想经历 alias_method 的麻烦(您真的不应该再使用它来解决该问题,Module#prepend 现在存在并且是一个更好的解决方案),你可以这样做:

For example, if you just want to wrap some existing method, without going through the hassle of alias_method (which you really shouldn't use any more for that problem, Module#prepend now exists and is a much better solution), you could do:

class Array
  prepend(Module.new do
    def [](*)
      puts 'Before-hook'
      super.tap { puts 'After-hook' }
    end
  end)
end

p [42][0]
# Before-hook
# After-hook
# => 42

这篇关于匿名模块可以用于什么目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆