ruby - 在 Ruby 中创建类方法的不同方式

标签 ruby class methods syntax class-method

示例 1:

class Dog
  def self.class_method
    :another_way_to_write_class_methods
  end
end

def test_you_can_use_self_instead_of_an_explicit_reference_to_dog
  assert_equal :another_way_to_write_class_methods, Dog.class_method
end

示例 2:

class Dog
  class << self
    def another_class_method
      :still_another_way
    end
  end
end

def test_heres_still_another_way_to_write_class_methods
  assert_equal :still_another_way, Dog.another_class_method
end

我可以知道在 Ruby 中首选哪种编写类方法的方式吗?为什么?是否存在优先于另一个的情况?

最佳答案

您要求使用不同的方法来创建类方法。这里有一些。

class A
  def self.a
    "A"
  end
end
A.a #=> "A"

class B
  class << self
    def b
      "B"
    end
  end
end
B.b #=> "B"

class C
  singleton_class.class_eval do
    def c
      "C"
    end
  end
end
C.c #=> "C"

module M
  def m
    "M"
  end
end

class D
  extend M
end
D.m #=> "M"

class E
  class << self
    include M
  end
end
E.m #=> "M"

class F
  singleton_class.instance_eval do
    define_method(:f) do
      "F"
    end
  end
end
F.f #=> "F"

如果:f是动态创建的,

class F
end
F.singleton_class.instance_eval do
   define_method(:f) do
     "F"
   end
end

或变体:

F.singleton_class.instance_eval "define_method(:f) { 'F' }"
F.f #=> "F"

class Class
  def k
    "K"
  end
end

class G
end
G.k #=> "K"

这里的问题是 Class 的所有实例方法(包括 :k)都可供所有类用作(类)方法,因为类是(H.class#=>类)。


class Object
  def o
    "O"
  end
end

class H
end
H.o #=> "O"
H.new.o #=> "O"

这个很有趣。 ObjectClass 的祖先(Class.ancestors #=> [Class, Module, Object, Kernel, BasicObject]),所以 ClassObject 继承实例方法:o。因此(从前面的例子来看),:oH 的一个类方法。但是,H也是Object的子类(H.superclass #=> Object),所以H继承实例方法Object#:o


至于哪个是“最好的”,这取决于。如果只创建几个类方法,大多数将使用 A。如果需要大量数据,我会使用 DB。如果要动态创建类方法,F 或一些变体。但是,我无法想象我会使用 GH 的情况。

关于ruby - 在 Ruby 中创建类方法的不同方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39936920/

相关文章:

python - 是否可以确定函数是哪个类的方法?

java - 我在生成贷款配置时缺少哪些循环?

ruby - 在 Ruby 中将十六进制转换为十进制

ruby-on-rails - gulp 插件 gulp-ruby-sass 不编译

ruby - ruby 存在哪些基于语法的解析器生成器工具?

javascript - 有没有办法在javascript中代理(拦截)一个类的所有方法?

python - 用于 Python 或 Ruby 的 Amazon Book API?

matlab - 在 Matlab 中访问@folder 函数

Excel VBA - 在类模块内键入

go - 接口(interface)作为结构中的字段,接口(interface)调用将输入作为相同结构的方法