Ruby 2.1 复数的写法

luikore · 2013年08月06日 · 最后由 msl12 回复于 2016年10月29日 · 5003 次阅读
require 'complex'
3r + 4i

必须要导入 complex 才能用这种字面量么? 导入一个模块能改变词法很不理解……

#1 楼 @ekim_sgra 哦,不用导入也可以

@luikore 这样才赞嘛!

ruby 好强大

  • Added integer and float literals: r, i, and ri.
    • "42r" and "3.14r" are evaluated as Rational(42, 1) and 3.14.rationalize, respectively. But exponential form with r suffix like "6.022e+23r" is not accepted because it is misleading.
    • "42i" and "3.14i" are evaluated as Complex(0, 42) and Complex(0, 3.14), respectively.
    • "42ri" and "3.14ri" are evaluated as Complex(0, 42r) and Complex(0, 3.14r), respectively.

Ruby2.0 中 Complex 和 Rational 已经在 core 了,但是 Decimal 还在 stand lib。

1% 的程序需要用到复数吧?

额?为何不设计成3 + 4i?这个才是真正的复数写法吧?

#8 楼 @iBachue 也可以啊,r 可以看作没做操作,只是 lift 到 rational 而已

Cant wait for Ruby 2.1

'3+4i'.to_c

blackanger Ruby 2.1 Features PDF 提及了此话题。 09月07日 18:56
需要 登录 后方可回复, 如果你还没有账号请 注册新账号