gpt4 book ai didi

ruby - 您更喜欢在 Ruby 中如何定义类方法?

转载 作者:数据小太阳 更新时间:2023-10-29 06:48:45 25 4
gpt4 key购买 nike

John Nunemaker最近写了关于 various ways to define class methods 的博客在 Ruby 中,给出这三种选择:

# Way 1
class Foo
def self.bar
puts 'class method'
end
end

# Way 2
class Foo
class << self
def bar
puts 'class method'
end
end
end

# Way 3
class Foo; end
def Foo.bar
puts 'class method'
end
  • 您首选的方法是什么?
  • 您还喜欢上述以外的东西吗?
  • 如果您使用不止一种方式,您在什么情况下使用它们?

最佳答案

我一直使用方法 1:

class Foo
def self.bar
puts 'class method'
end
end

它并不冗长,而且它使方法保持在类的相同上下文中。

关于ruby - 您更喜欢在 Ruby 中如何定义类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/881821/

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