File: to_r_spec.rb

package info (click to toggle)
ruby3.3 3.3.8-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 153,620 kB
  • sloc: ruby: 1,244,308; ansic: 836,474; yacc: 28,074; pascal: 6,748; sh: 3,913; python: 1,719; cpp: 1,158; makefile: 742; asm: 712; javascript: 394; lisp: 97; perl: 62; awk: 36; sed: 23; xml: 4
file content (58 lines) | stat: -rw-r--r-- 1,701 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
require_relative '../../spec_helper'

describe "String#to_r" do
  it "returns a Rational object" do
    String.new.to_r.should be_an_instance_of(Rational)
  end

  it "returns (0/1) for the empty String" do
    "".to_r.should == Rational(0, 1)
  end

  it "returns (n/1) for a String starting with a decimal _n_" do
    "2".to_r.should == Rational(2, 1)
    "1765".to_r.should == Rational(1765, 1)
  end

  it "ignores trailing characters" do
    "2 foo".to_r.should == Rational(2, 1)
    "1765, ".to_r.should == Rational(1765, 1)
  end

  it "ignores leading spaces" do
    " 2".to_r.should == Rational(2, 1)
    "  1765, ".to_r.should == Rational(1765, 1)
  end

  it "does not ignore arbitrary, non-numeric leading characters" do
    "The rational form of 33 is...".to_r.should_not == Rational(33, 1)
    "a1765, ".to_r.should_not == Rational(1765, 1)
  end

  it "treats leading hyphen as minus signs" do
    "-20".to_r.should == Rational(-20, 1)
  end

  it "does not treat a leading period without a numeric prefix as a decimal point" do
    ".9".to_r.should_not == Rational(8106479329266893, 9007199254740992)
  end

  it "understands decimal points" do
    "3.33".to_r.should == Rational(333, 100)
    "-3.33".to_r.should == Rational(-333, 100)
  end

  it "ignores underscores between numbers" do
    "190_22".to_r.should == Rational(19022, 1)
    "-190_22.7".to_r.should == Rational(-190227, 10)
  end

  it "understands a forward slash as separating the numerator from the denominator" do
    "20/3".to_r.should == Rational(20, 3)
    " -19.10/3".to_r.should == Rational(-191, 30)
  end

  it "returns (0/1) for Strings it can't parse" do
    "glark".to_r.should == Rational(0,1)
  end
end