【发布时间】:2015-04-15 19:16:23
【问题描述】:
我有一堂课:
class MyClass
def self.create_array
variable = ['one', 'two', 'three']
# I had:
# variable.each {|v| v.upcase}
# but want to do:
second_method(variable)
# or like this:
variable.second_method
# of course without parameter 'var' in second option
end
def second_method (var)
var.map {|v| v.upcase}
end
end
puts MyClass.create_array
# of course:
=> undefined method `second_method' for MyClass:Class (NoMethodError)
所以我只是想知道如何将 second_method 合并到第一个中。
只有当我这样做时它才有效:
class MyClass
def self.create_array
variable = ['one', 'two', 'three']
MyClass.second_method(variable)
end
def self.second_method (var)
var.map {|v| v.upcase}
end
end
puts MyClass.create_array
为什么它只在我在课堂上调用时才有效?我想在我的变量上调用它。请赐教!
编辑
在以下位置创建方法是否有意义:
class Array
def second_method
#content
end
end
【问题讨论】:
-
second_method 不能在类方法中调用,因为它缺少实例。类的方法总是需要类的实例,否则不能调用。另请阅读railstips.org/blog/archives/2009/05/11/…
-
不会对类数组进行猴子补丁,当在包含非字符串的数组上调用时会出错,这也是你的类中需要的功能,而不是数组中
-
@peter 所以我会在下面听从你的建议,谢谢!