如果方法和变量都具有相同的名称,它将使用该变量.
hello = "hello from variable"
def hello
"hello from method"
end
puts hello
Run Code Online (Sandbox Code Playgroud)
有可能以某种方式使用该方法而不更改名称?
我刚开始使用IronRuby(但是当我在普通Ruby中测试它时,行为似乎是一致的)我的.NET应用程序中的DSL - 作为其中的一部分,我定义了通过define_method从DSL调用的方法.
但是,在调用以大写字母开头的方法时,我遇到了关于可选parens的问题.
鉴于以下计划:
class DemoClass
define_method :test do puts "output from test" end
define_method :Test do puts "output from Test" end
def run
puts "Calling 'test'"
test()
puts "Calling 'test'"
test
puts "Calling 'Test()'"
Test()
puts "Calling 'Test'"
Test
end
end
demo = DemoClass.new
demo.run
Run Code Online (Sandbox Code Playgroud)
在控制台中运行此代码(使用普通红宝石)会产生以下输出:
ruby .\test.rb
Calling 'test'
output from test
Calling 'test'
output from test
Calling 'Test()'
output from Test
Calling 'Test'
./test.rb:13:in `run': uninitialized constant DemoClass::Test (NameError)
from ./test.rb:19:in `<main>'
Run Code Online (Sandbox Code Playgroud)
我意识到Ruby约定是常量以大写字母开头,并且Ruby中方法的一般命名约定是小写的.但是parens目前正在杀死我的DSL语法.
有没有解决这个问题的方法?