instance method
String#to_r
() -> ::Rational
str.to_r → rational
rational.c
View on GitHub ↗
static VALUE
string_to_r(VALUE self)
{
VALUE num;
rb_must_asciicompat(self);
num = parse_rat(RSTRING_PTR(self), RSTRING_END(self), 0, TRUE);
if (RB_FLOAT_TYPE_P(num) && !FLOAT_ZERO_P(num))
rb_raise(rb_eFloatDomainError, "Infinity");
return num;
}
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.