Permalink
Browse files

Merge pull request #2010 from kachick/fix/Range-first_accept_argument…

…_on_X19

Range#first has different behavior with Range#begin from Ruby 1.9
  • Loading branch information...
2 parents f635005 + eaa08a2 commit 8e3d14fc84e01652e39eedb97e2aec941e2b683e Brian Ford committed Nov 13, 2012
Showing with 48 additions and 1 deletion.
  1. +0 −1 kernel/common/range.rb
  2. +2 −0 kernel/common/range18.rb
  3. +4 −0 kernel/common/range19.rb
  4. +42 −0 spec/ruby/core/range/first_spec.rb
View
@@ -106,7 +106,6 @@ def each(&block)
end
attr_reader :begin
- alias_method :first, :begin
def hash
excl = @excl ? 1 : 0
View
@@ -3,6 +3,8 @@
class Range
alias_method :===, :include?
+ alias_method :first, :begin
+
protected
def can_iterate_from?(object)
View
@@ -7,6 +7,10 @@ def ===(value)
alias_method :cover?, :include?
+ def first(n=undefined)
+ n.equal?(undefined) ? @begin : super
+ end
+
def max(&block)
raise TypeError, "cannot exclude non Integer end value" if @end.kind_of?(Float) && @excl
@@ -3,4 +3,46 @@
describe "Range#first" do
it_behaves_like(:range_begin, :first)
+
+ ruby_version_is "1.9" do
+ it "returns the first count elements if given a count" do
+ (0..2).first(2).should == [0, 1]
+ end
+
+ it "returns an empty array when passed count on an empty range" do
+ (0...0).first(0).should == []
+ (0...0).first(1).should == []
+ (0...0).first(2).should == []
+ end
+
+ it "returns an empty array when passed count == 0" do
+ (0..2).first(0).should == []
+ end
+
+ it "returns an array containing the first element when passed count == 1" do
+ (0..2).first(1).should == [0]
+ end
+
+ it "raises an ArgumentError when count is negative" do
+ lambda { (0..2).first(-1)}.should raise_error(ArgumentError)
+ end
+
+ it "returns the entire array when count > length" do
+ (0..2).first(4).should == [0, 1, 2]
+ end
+
+ it "tries to convert the passed argument to an Integer using #to_int" do
+ obj = mock('to_int')
+ obj.should_receive(:to_int).and_return(2)
+ (0..2).first(obj).should == [0, 1]
+ end
+
+ it "raises a TypeError if the passed argument is not numeric" do
+ lambda { (0..2).first(nil) }.should raise_error(TypeError)
+ lambda { (0..2).first("a") }.should raise_error(TypeError)
+
+ obj = mock("nonnumeric")
+ lambda { (0..2).first(obj) }.should raise_error(TypeError)
+ end
+ end
end

0 comments on commit 8e3d14f

Please sign in to comment.