gpt4 book ai didi

ruby - 我怎样才能在 ruby​​ 中实现这个结果?

转载 作者:数据小太阳 更新时间:2023-10-29 08:35:55 24 4
gpt4 key购买 nike

我正在阅读 Sequel 的文档,我对以下代码片段中使用的技术感到好奇:

class Post < Sequel::Model(:my_posts)
(...)
end

Sequel::Model(:my_posts) 设置模型的数据库表。我特别好奇 Model(:my_posts) 中的括号。我喜欢这个界面,但我该如何实现呢?有点奇怪……好像Model可以作为方法来调用……这是什么技术?有人可以给我举个例子吗?

最佳答案

通常当您使用 :: 时对于模块或类,ruby 将尝试在 :: 之后查找表达式在常量中。

Example::First => as constant
Example::First() => as method

运行这段代码:

module Example
class << self
def First(a)
puts a
end
end

module First
end
end

用法:

Example::First(1) # => prints 1

当您使用 class << self 时您打开 self 的类,以便可以为当前的 self 对象重新定义方法(在类或模块主体内是类或模块本身)。好好读书question/answers在 SO 上。

It's good practice, while not mandatory, to start the method name with a lower-case character, because names that start with capital letters are constants in Ruby. It's still possible to use a constant name for a method, but you won't be able to invoke it without parentheses, because the interpeter will look-up for the name as a constant

来自 What are the restrictions for method names in Ruby?

关于ruby - 我怎样才能在 ruby​​ 中实现这个结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41067427/

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