Ruby语法问题:Rational(a,b)和Rational.new!(a,b) [英] Ruby syntax question: Rational(a, b) and Rational.new!(a, b)

查看:313
本文介绍了Ruby语法问题:Rational(a,b)和Rational.new!(a,b)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我在 Rational 类中遇到了奇怪的ruby语法: / p>

Today I came across the strange ruby syntax in the Rational class:

Rational(a,b)

(注意,与正常的Ruby语法相比,不存在 .new()部分)。与正常的 new 语法相比,这是什么意思?更重要的是,我如何在自己的代码中实现这样的东西,为什么我会实现这样的东西?特别是对于 Rational 类,为什么使用这种语法而不是正常的实例化?为什么 new 方法在理性类中是私有的? (我怎么/为什么要在我自己的ruby代码中这样做?)
提前感谢您的答案,特别是因为我问了这么多问题。

(Notice the absence of the .new()portion compared to the normal Ruby syntax). What does this mean, precisely, compared to the normal new syntax? More importantly, how do I implement something like this in my own code, and why would I implement something like this? Specifically for the Rational class, why is this syntax used instead of the normal instantiation? And why is the new method private in the rational class? (And how/why would I do this in my own ruby code?) Thanks in advance for your answers, especially since I've asked so many questions.

推荐答案

所有你需要做的是声明一个与你的类同名的全局函数。这是rational.rb所做的:

All you have to do is declare a global function with the same name as your class. And that is what rational.rb does:

def Rational(a, b = 1)
  if a.kind_of?(Rational) && b == 1
    a
  else
    Rational.reduce(a, b)
  end
end

使构造函数私有:

private :initialize

,类似的 new 方法:

private_class_method :new

我认为 Rational.new 可以保持公开,并做做 Rational()方法将其参数转换为实例与 Array() String()等是一致的。这很容易实现和理解。

I suppose Rational.new could be kept public and made to do what Rational() does, but having a method that turns its arguments into instances is consistent with Array(), String(), etc. It's a familiar pattern that's easy to implement and understand.

这篇关于Ruby语法问题:Rational(a,b)和Rational.new!(a,b)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆