ruby - 如何调用名为 [] 的 ruby​​ 函数?

标签 ruby

我是 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/

相关文章:

ruby - 使用参数与 ruby​​ require

Ruby:当我使用递归查找素数时出错

ruby - 在 Ruby 中获取响应大小的优化方法?

arrays - 当存在重复值时,如何比较数组中的整数索引?

ruby-on-rails - 如何在 Rails 中的 CSV 解析期间更改编码

ruby-on-rails - Ruby on Rails - Base64 的外部图像 Url

ruby-on-rails - Rails 测试模型说 'Expected false to be truthy'

脚本底部的 Ruby 方法?

ruby - 当 “wrong number of arguments”出现时,Ruby自动添加参数。

ruby-on-rails - Rails4 : Why resque worker is not picking up jobs