我最近在这个上下文中遇到了 Ruby EOB
/构造(来自 Ruby id3 库):-EOB
def initialize(...)
# ...
instance_eval <<-EOB
class << self
def parse
# ...
# Method code
# ...
end
EOB
self.parse # now we're using the just defined parsing routine
# ...
end
我知道代码用于动态生成方法,但我想知道是否可以EOB
在方法中使用代码段。我想编写一个生成其他方法代码的方法,该代码将包含在另一个类中。这听起来有点令人困惑,我将尝试用一些简化的代码示例来说明我的意图:
# This class reads the code of another
# Ruby class and injects some methods
class ReadAndInject
# The method which defines another method
def get_code_to_be_injected
"\tdef self.foo\n"+
"\t\tputs 'bar'\n"+
"\tend\n"
end
# Main entry point, reads a generated Ruby Class
# and injects specific methods within it
def read_and_inject
# Assume placeholder for currently read line,
# add the generated code within
current_line += "\n#{get_code_to_be_injected}"
end
end # class ReadAndInject
这会起作用,因为要注入的方法已正确添加。然而,我想知道使用该EOB
构造是否会产生一些优势(例如,代码的更好可见性,因为不必添加繁琐的选项卡或字符串连接。
总而言之,这是一个很好的用例EOB
吗?这似乎是一个阴暗但功能强大的构造,我已经避开了它,用谷歌搜索并在 stackoverflow 上搜索了它,但除了来自 RubyCocoa的代码示例之外,没有返回任何重要的代码示例。我最近才开始在 Ruby 中使用元结构,所以请保持温和 :-)
提前致谢!