Ruby 2.1 复数的写法

luikore · August 06, 2013 · Last by msl12 replied at October 29, 2016 · 5005 hits
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 in Ruby 2.1 Features PDF mention this topic. 07 Sep 18:56
You need to Sign in before reply, if you don't have an account, please Sign up first.