Skip to content
instance method

String#to_r

() -> ::Rational
str.to_r → rational

Returns the result of interpreting leading characters in self as a rational value:

Example
'123'.to_r       # => (123/1)   # Integer literal.
'300/2'.to_r     # => (150/1)   # Rational literal.
'-9.2'.to_r      # => (-46/5)   # Float literal.
'-9.2e2'.to_r    # => (-920/1)  # Float literal.

Ignores leading and trailing whitespace, and trailing non-numeric characters:

Example
' 2 '.to_r       # => (2/1)
'21-Jun-09'.to_r # => (21/1)

Returns Rational zero if there are no leading numeric characters.

Example
'BWV 1079'.to_r  # => (0/1)

NOTE: '0.3'.to_r is equivalent to 3/10r, but is different from 0.3.to_r:

Example
'0.3'.to_r # => (3/10)
3/10r      # => (3/10)
0.3.to_r   # => (5404319552844595/18014398509481984)

Related: see Converting to Non-String.

See also #to_json_raw_object #to_s #to_json_raw #to_str also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0