【发布时间】:2017-02-17 14:45:00
【问题描述】:
示例 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 中首选哪种编写类方法的方式,为什么?是否存在优先于另一个的情况?
【问题讨论】:
-
你也可以写
def Dog.class_method;end,你也可以写在类块之外。
标签: ruby class methods syntax class-method