我是 Ruby 的新手,如果这个问题很明显,请原谅。
我正在使用一个我不理解其函数签名的模块。我该如何调用这个函数?
module Facter
...
def self.[](name)
collection.fact(name)
end
...
在我的代码中,我想引用一些应该在 collection.fact 中的东西,在这个 Facter 模块中。我使用什么语法来调用这个函数?
干杯
最佳答案
它是这样工作的:
class MyModule
def self.[](arg)
puts arg
end
end
MyModule["Hello world"] # will print Hello world
请看官方文档:
https://ruby-doc.org/core/doc/syntax/methods_rdoc.html
Additionally, methods for element reference and assignment may be defined:
[]
and[]=
respectively. Both can take one or more arguments, and element reference can take none.class C def [](a, b) puts a + b end def []=(a, b, c) puts a * b + c end end obj = C.new obj[2, 3] # prints "5" obj[2, 3] = 4 # prints "10"
关于文档中的例子
# From docs
obj[2, 3]
# It's the same as
obj.[](2, 3)
更有趣的例子
# From docs
obj[2, 3] = 4
# will print 10
# => 4
# It's the almost as
obj.[]=(2, 3, 4)
# will print 10
# => nil
正如您在调用 obj[2, 3] = 4
时看到的那样,Ruby 将 =
之后的值作为 []= 的最后一个参数
方法并将其作为方法结果返回
并且不管方法体中是否有return
。例如
class C
def []=(a, b, c)
puts "Before return"
return 12
puts "After return"
end
end
obj = C.new
obj[2, 3] = 4
# will print Before return
# => 4
obj.[]=(2, 3, 4)
# will print Before return
# => 12
最好用一个以上的参数来定义这样的方法。从技术上讲,你只能有一个,但调用将像这样 obj[] = 1
关于ruby - 如何调用名为 [] 的 ruby 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70979506/