gpt4 book ai didi

ruby - Ruby 的 EOB 构造的用例

转载 作者:太空宇宙 更新时间:2023-11-03 18:29:20 25 4
gpt4 key购买 nike

我最近在这个上下文中遇到了 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

这会起作用,因为要注入(inject)的方法已正确添加。然而,我想知道使用 EOB 结构是否会产生一些优势(例如,更好的代码可见性,因为不必添加繁琐的制表符或字符串连接。

总而言之,这是 EOB 的一个很好的用例吗?这似乎是一个阴暗而强大的结构,我有 ducked它,google 和 stackoverflow'd 除了 one from RubyCocoa 之外还没有重要的代码示例。被退回。我最近才开始在 Ruby 中使用元结构,所以请保持温和:-)

提前致谢!

最佳答案

这些被称为 "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

关于ruby - Ruby 的 EOB 构造的用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6486891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com