Ruby的EOB结构的用例

时间:2011-06-26 21:34:13

标签: ruby metaprogramming heredoc

我最近遇到了这个上下文中的Ruby EOB / -EOB构造(来自Ruby id3 library):

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的一个很好的用例吗? 它似乎是一个阴暗但强大的构造,我ducked它,谷歌搜索和stackoverflow它但没有返回除one from RubyCocoa以外的重要代码示例。我最近才开始在Ruby中使用元构造,所以请温柔: - )

提前致谢!

1 个答案:

答案 0 :(得分:3)

这些被称为"here documents",它们由多种语言支持,并允许您创建多行字符串。您实际上可以使用任何分隔符,而不仅仅是EOB。 Ruby为heredocs提供了一些额外的功能:例如,-中的<<-EOB允许您缩进分隔符。

您可以这样使用它:

def code_to_be_injected
  <<-EOS
    def self.foo
      puts 'bar'
    end
  EOS
end

Ruby中的一些其他功能:

myvar = 42
<<EOS
variable: #{myvar}
EOS #=> "variable: 42"

<<'EOS'
variable: #{myvar}
EOS #=> "variable: #{myvar}"

print <<A, <<B
This will appear first
A
and this second
B