Ruby:定义使用语法的方法时的奇怪行为

Ruby:定义使用语法的方法时的奇怪行为,ruby,syntax,metaprogramming,Ruby,Syntax,Metaprogramming,目前我正在研究一些元编程思想,让我先介绍一下: 我可以将类或模块中的字符串“template”定义为常量,然后像这样使用它: class Test1 ConstString = %(the string in here is %{instring}) end puts Test1::ConstString % { instring: "test" } #=> the string in here is test 问题是 a。基于基准测试,仅定义一个函数就可以以3倍的速度完成相同的事情

目前我正在研究一些元编程思想,让我先介绍一下: 我可以将
模块
中的字符串“template”定义为
常量
,然后像这样使用它:

class Test1
  ConstString = %(the string in here is %{instring})
end
puts Test1::ConstString % { instring: "test" }
#=> the string in here is test
问题是

a。基于基准测试,仅定义一个函数就可以以3倍的速度完成相同的事情(基准测试为1000000.times):

b。我希望将这些函数与常规函数分开,因为我希望如何使用它们

所以我决定创建一个新类来继承Proc。。。 并包含一个
模块
,以引入百分比/模语法

module ProcPercentSyntax
  def %(*args)
    self.call(*args)
  end
end
class TestFromProc < Proc
  include ProcPercentSyntax
end


class Test2
  ConstString = TestFromProc.new { |x, y| %(this is a string with #{x} and #{y}) }
end
但是

#=> this is a string with test and 
#=> this is a string with test and 
令人不安地没有抛出任何错误

为了确保这不是另一个问题,我继续这样做:

module ProcNotPercentSyntax
  def make(*args)
    self.call(*args)
  end
end

而且

#=> this is a string with test and test2
请原谅这个问题的拖沓性,我将把我的意图总结如下:

当使用
%
作为方法名称时,为什么该方法似乎遗漏了第二个给定参数

但是

#=> this is a string with test and 
#=> this is a string with test and 
不,这不是结果。结果是:

# this is a string with test and 
# test2
#=> nil
令人不安地没有抛出任何错误

为什么会有错误?使用两个参数调用
put
是完全合法的,这就是您在这里所做的。你期待什么

puts 1+1, 3
打印?完全一样

当使用
%
作为方法名称时,为什么该方法似乎遗漏了第二个给定参数

%
是类似于

但是

#=> this is a string with test and 
#=> this is a string with test and 
不,这不是结果。结果是:

# this is a string with test and 
# test2
#=> nil
令人不安地没有抛出任何错误

为什么会有错误?使用两个参数调用
put
是完全合法的,这就是您在这里所做的。你期待什么

puts 1+1, 3
打印?完全一样

当使用
%
作为方法名称时,为什么该方法似乎遗漏了第二个给定参数


%
是一个类似于
的二进制运算符。在这种不明确的情况下,您不需要括号吗?请尝试更改代码,使其以这种方式工作:
将Test2::ConstString%[“test”,“Test2”]
。可能String的
%
方法只接受一个参数。它确实可以处理显式传递的
[]
,但是我想知道为什么
。make
示例接受隐式
“String”,“String”
而“%`不接受,如果有一种方法可以让它接受隐式。在ProcPercentSyntax的
%
方法中,是什么给了
p args
,在这种情况下,我可能不得不接受你的数组语法。在这种模棱两可的情况下,你不需要括号吗?试着改变你的代码,使它以这种方式工作:
puts Test2::ConstString%[“test”,“Test2”]
。可能String的
%
方法只接受一个参数。它确实可以处理显式传递的
[]
,但是我想知道为什么
。make
示例接受隐式
“String”,“String”
而“%`不接受,如果有一种方法可以让它接受隐式。在ProcPercentSyntax的
%
方法中,是什么给了
p args
,在这种情况下,我可能不得不接受您的数组语法。我的方法中有很多
put
,但忽略了通过对象上的测试
put
输出的额外行。你的回答给了我完成代码所需的洞察力,谢谢!我的方法中有很多
put
,忽略了通过对象上的测试
put
输出的附加行。你的回答给了我完成代码所需的洞察力,谢谢!