通过点调用Ruby函数

时间:2015-10-03 11:22:00

标签: ruby

我想调用一个名为my_format_number的函数,如:

num = 5.5
formated_num = num.my_format_number

我怎么能在Ruby中做到这一点?这些类型的函数的名称是什么?

3 个答案:

答案 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

这是因为我们定义了Float100的数量(正如错误消息告诉我们的那样)不是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