summaryrefslogtreecommitdiff
path: root/spec/ruby/core/hash/transform_values_spec.rb
blob: 0c9e43d621420d717d8fa7d7cb03a9bcd39d32e8 (plain)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
require File.expand_path('../../../spec_helper', __FILE__)

ruby_version_is "2.4" do
  describe "Hash#transform_values" do
    before :each do
      @hash = { a: 1, b: 2, c: 3 }
    end

    it "returns new hash" do
      ret = @hash.transform_values(&:succ)
      ret.should_not equal(@hash)
      ret.should be_an_instance_of(Hash)
    end

    it "sets the result as transformed values with the given block" do
      @hash.transform_values(&:succ).should ==  { a: 2, b: 3, c: 4 }
    end

    context "when no block is given" do
      it "returns a sized Enumerator" do
        enumerator = @hash.transform_values
        enumerator.should be_an_instance_of(Enumerator)
        enumerator.size.should == @hash.size
        enumerator.each(&:succ).should == { a: 2, b: 3, c: 4 }
      end
    end

    it "returns a Hash instance, even on subclasses" do
      klass = Class.new(Hash)
      h = klass.new
      h[:foo] = 42
      r = h.transform_values{|v| 2 * v}
      r[:foo].should == 84
      r.class.should == Hash
    end
  end

  describe "Hash#transform_values!" do
    before :each do
      @hash = { a: 1, b: 2, c: 3 }
      @initial_pairs = @hash.dup
    end

    it "returns self" do
      @hash.transform_values!(&:succ).should equal(@hash)
    end

    it "updates self as transformed values with the given block" do
      @hash.transform_values!(&:succ)
      @hash.should ==  { a: 2, b: 3, c: 4 }
    end

    it "partially modifies the contents if we broke from the block" do
      @hash.transform_values! do |v|
        break if v == 3
        100 + v
      end
      @hash.should == { a: 101, b: 102, c: 3}
    end

    context "when no block is given" do
      it "returns a sized Enumerator" do
        enumerator = @hash.transform_values!
        enumerator.should be_an_instance_of(Enumerator)
        enumerator.size.should == @hash.size
        enumerator.each(&:succ)
        @hash.should == { a: 2, b: 3, c: 4 }
      end
    end

    describe "on frozen instance" do
      before :each do
        @hash.freeze
      end

      it "raises a RuntimeError on an empty hash" do
        ->{ {}.freeze.transform_values!(&:succ) }.should raise_error(RuntimeError)
      end

      it "keeps pairs and raises a RuntimeError" do
        ->{ @hash.transform_values!(&:succ) }.should raise_error(RuntimeError)
        @hash.should == @initial_pairs
      end

      context "when no block is given" do
        it "does not raise an exception" do
          @hash.transform_values!.should be_an_instance_of(Enumerator)
        end
      end
    end
  end
end