当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Kernel.Rational用法及代码示例


本文简要介绍ruby语言中 Kernel.Rational 的用法。

用法

Rational(x, y, exception: true) → rational or nil
Rational(arg, exception: true) → rational or nil

返回 x/yarg 作为 Rational

Rational(2, 3)   #=> (2/3)
Rational(5)      #=> (5/1)
Rational(0.5)    #=> (1/2)
Rational(0.3)    #=> (5404319552844595/18014398509481984)

Rational("2/3")  #=> (2/3)
Rational("0.3")  #=> (3/10)

Rational("10 cents")  #=> ArgumentError
Rational(nil)         #=> TypeError
Rational(1, nil)      #=> TypeError

Rational("10 cents", exception: false)  #=> nil

字符串形式的语法:

string form = extra spaces , rational , extra spaces ;
rational = [ sign ] , unsigned rational ;
unsigned rational = numerator | numerator , "/" , denominator ;
numerator = integer part | fractional part | integer part , fractional part ;
denominator = digits ;
integer part = digits ;
fractional part = "." , digits , [ ( "e" | "E" ) , [ sign ] , digits ] ;
sign = "-" | "+" ;
digits = digit , { digit | "_" , digit } ;
digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
extra spaces = ? \s* ? ;

另见 String#to_r

相关用法


注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Kernel.Rational。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。