1 require File.dirname(__FILE__) + '/../../spec_helper'
3 describe "Enumerable#max_by" do
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
31 it "returns nil if #each yields no objects" do
32 EnumEmpty.new.max_by {|o| o.nonesuch }.should == nil
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'
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
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
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