本文簡要介紹ruby語言中 String.to_r
的用法。
用法
to_r → rational
返回將str
中的前導字符解釋為有理數的結果。忽略有效數字末尾的前導空格和無關字符。數字序列可以用下劃線分隔。如果 str
的開頭沒有有效數字,則返回零。此方法從不引發異常。
' 2 '.to_r #=> (2/1)
'300/2'.to_r #=> (150/1)
'-9.2'.to_r #=> (-46/5)
'-9.2e2'.to_r #=> (-920/1)
'1_234_567'.to_r #=> (1234567/1)
'21 June 09'.to_r #=> (21/1)
'21/06/09'.to_r #=> (7/2)
'BWV 1079'.to_r #=> (0/1)
注意:“0.3”.to_r 與 0.3.to_r 不同。前者等價於“3/10”.to_r,但後者並非如此。
"0.3".to_r == 3/10r #=> true
0.3.to_r == 3/10r #=> false
另見 Kernel#Rational
。
相關用法
- Ruby String.to_sym用法及代碼示例
- Ruby String.to_i用法及代碼示例
- Ruby String.to_c用法及代碼示例
- Ruby String.to_d用法及代碼示例
- Ruby String.to_f用法及代碼示例
- Ruby String.tr用法及代碼示例
- Ruby String.tr_s用法及代碼示例
- Ruby String.match?用法及代碼示例
- Ruby String.unpack用法及代碼示例
- Ruby String.scan用法及代碼示例
- Ruby String.dump用法及代碼示例
- Ruby String.oct用法及代碼示例
- Ruby String.size用法及代碼示例
- Ruby String.scrub用法及代碼示例
- Ruby String.chop用法及代碼示例
- Ruby String.bytesize用法及代碼示例
- Ruby String.count用法及代碼示例
- Ruby String.string <=>用法及代碼示例
- Ruby String.ascii_only?用法及代碼示例
- Ruby String.downcase用法及代碼示例
- Ruby String.capitalize用法及代碼示例
- Ruby String.length用法及代碼示例
- Ruby String.lines用法及代碼示例
- Ruby String.unicode_normalize用法及代碼示例
- Ruby String.center用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 String.to_r。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。