1

我最近在这个上下文中遇到了 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 中使用元结构,所以请保持温和 :-)

提前致谢!

4

1 回答 1

3

这些被称为“这里的文档”,由多种语言支持,并允许您制作多行字符串。您实际上可以使用任何分隔符,而不仅仅是 EOB。Ruby 为 heredocs 提供了一些额外的功能:例如,-in<<-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
于 2011-06-26T21:48:10.980 回答