Updated RubySpec submodule to 9f66d0b1.
[rbx.git] / spec / core / enumerable / max_by_spec.rb
blob10a32c056a7e6900e947f63326db5880a0ace6cf
1 require File.dirname(__FILE__) + '/../../spec_helper'
3 describe "Enumerable#max_by" do
4   class EnumMaxBy
5     def initialize(num)
6       @num = num
7     end
9     attr_accessor :num
11     # Reverse comparison
12     def <=>(other)
13       other.num <=> @num
14     end
15   end
17   class EnumEmpty
18     include Enumerable
20     def each()
21       # Nothing to do
22     end
23   end
25   # Array is OK here because we know it does not override
27   it "requires a block" do
28     lambda { [1, 2, 3].max_by }.should raise_error
29   end
31   it "returns nil if #each yields no objects" do
32     EnumEmpty.new.max_by {|o| o.nonesuch }.should == nil
33   end
35   it "returns the object for whom the value returned by block is the largest" do
36     %w[1 2 3].max_by {|obj| obj.to_i }.should == '3'
37     %w[three five].max_by {|obj| obj.length }.should == 'three'
38   end
40   it "returns the object that appears first in #each in case of a tie" do
41     # We assume that an Array will yield in order
42     a, b, c = '1', '2', '2'
43     [a, b, c].max_by {|obj| obj.to_i }.equal?(b).should == true
44   end
46   it "uses max.<=>(current) to determine order" do
47     a, b, c = EnumMaxBy.new(1), EnumMaxBy.new(2), EnumMaxBy.new(3)
49     # Just using self here to avoid additional complexity
50     [a, b, c].max_by {|obj| obj }.should == a
51   end
53   it "is able to return the maximum for enums that contain nils" do
54     [nil, nil, true].max_by {|o| o.nil? ? 0 : 1 }.should == true
55     [nil, nil, true].max_by {|o| o.nil? ? 1 : 0 }.should == nil
56   end
57 end