我想调用一个名为my_format_number
的函数,如:
num = 5.5
formated_num = num.my_format_number
我怎么能在Ruby中做到这一点?这些类型的函数的名称是什么?
答案 0 :(得分:3)
这些类型的函数的名称是什么?
在面向对象的编程中(独立于编程语言),绑定到对象的函数(通常通过对象的类)被称为“方法”。但是Some Ruby documentation calls all functions 'methods'。为了区分,我将使用'方法'仅表示绑定功能,并且通常将功能称为'功能'。
未绑定到对象的函数通常称为“自由函数”。
方法绑定的对象称为方法' receiver'。
我怎么能在Ruby中做到这一点?
在Ruby中,方法总是实例方法:它们在类上定义,但作用于类的实例。 (即,接收者必须是一个实例。)除了在C / C ++或Java中,Ruby中的所有值都是对象(类的实例),因此每个值都有一个类。
类是值/对象/实例的类型。它确定(在某种程度上)值的语义,以及该值上可用的方法。
5.5
的班级是什么?让我们来看看:
(5.5).class()
# => Float
(较短的5.5.class
也会起作用,但有点难以理解。)
Float
是Ruby的浮点数内置类。
Float
类Ruby中的类定义可以拆分和分发。除了已经生效的块之外,每个块在解释后都会生效,这意味着您可以在运行时修改类。这被称为“猴子补丁”。或者“重新开课”。
让我们重新打开Float
课程并添加my_format_number
方法。我决定它将返回一个字符串:
class Float
def my_format_number
return "The number is #{self} and #{self} is the number."
end
end
(可以跳过字符串前面的return
,因为Ruby函数会隐式返回它们评估的最后一个表达式。)
现在,您可以在所有Float
值上调用新方法:
num = 5.5
formatted_num = num.my_format_number()
puts(formatted_num)
# The number is 5.5 and 5.5 is the number.
我们甚至不需要变量,可以直接在值文字上调用该方法:
puts 7.8.my_format_number
# The number is 7.8 and 7.8 is the number.
但是,它不会为所有数字工作:
100.my_format_number
# NoMethodError: undefined method `my_format_number' for 100:Fixnum
# from (irb):15
# from :0
这是因为我们定义了Float
和100
的数量(正如错误消息告诉我们的那样)不是Float
而是Fixnum
(a特殊的Integer
)。
您当然现在也可以定义Fixnum
的功能。但有些数字既不是Fixnum
也不是Float
。因此,将功能放在某个中心位置是有意义的。
我们可以修补Ruby的主类Object
。但这样就可以了
"foobar".my_format_number
返回"The number is foobar and foobar is the number."
,这没有任何意义,因为foobar
不是数字。我只希望我们的方法格式化数字。
让我们看看Fixnum
的类是如何构建的:
Fixnum.superclass()
# => Integer
Fixnum.superclass().superclass() # equivalent to `Integer.superclass`
# => Numeric
Fixnum.superclass().superclass().superclass() # equivalent to `Numeric.superclass`
# => Object
superclass
方法只给我们一个直接的祖先。使用Ruby模块,可以实现多重继承,因此我们可以获得更多结果:
Fixnum.ancestors
# => [Fixnum, Integer, Precision, Numeric, Comparable, Object, Kernel]
让我们看看重叠是什么
Float.ancestors()
# => [Float, Precision, Numeric, Comparable, Object, Kernel]
Comparable
可能比数字更通用,而Precision
可能过于具体甚至有些不相关。 (它可能是一个模块。)让我们修改Numeric
因此(从它的名字猜测)听起来像是正确的抽象层次。的确,the documentation称之为
顶级数字类。
因此,与以前非常相似,
class Numeric
def my_format_number
return "The number is #{self} and #{self} is the number."
end
end
现在
100.my_format_number
# => "The number is 100 and 100 is the number."
如果您想知道我们在第二次猴子修补中添加了该方法的所有课程,请查看Look up all descendants of a class in Ruby。
答案 1 :(得分:1)
class Float
def my_format_number
...
end
end
答案 2 :(得分:0)
我想我将添加一个简单的示例,以演示如何使用.
def plus_two
self + 2
end
2.plus_two
=> 4