开发者

Use cases for Ruby's EOB construct

开发者 https://www.devze.com 2023-03-15 07:57 出处:网络
I recently came across the Ruby EOB / -EOB construct within this context (from the Ruby id3 library) :

I recently came across the Ruby EOB / -EOB construct within this context (from the 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

I understand that the code is used to generate a method on the fly, yet I would like to know if it would be possible to use the EOB snippet within a method. I would like to write a method which generates some other method code , which is to be included in yet another class. This sounds a bit confusing, I'll try to illustrate my intention with some simplified code samples :

# 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

This would work, since the method to be injected is added correctly. Yet I was wondering if using the EOB construct would yield some advantages (e.g. better visibility of the code, since no cumbersome tabs or string concatenations would have to be added.

To conclude, is this a good use case for EOB ? It seems like a shady yet powerful construct, I've ducked it, googled and stackoverflow'd it yet no significant code samples other than one from RubyCocoa were return开发者_如何学运维ed. I've only recently started to use meta constructs in Ruby, so please be gentle :-)

Thanks in advance!


These are called "here documents", which are supported by several languages, and allow you to make a multi-line string. You can actually use any delimiter, not just EOB. Ruby has some extra features for heredocs: for example, the - in <<-EOB allows you to indent the delimiter.

You might use it like this:

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

Some additional features in 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号