Skip to content
Browse files

Clearer String#first and #last edge cases. Fix that foo.first(0) == i…

…nstead of foo.
  • Loading branch information...
1 parent dc69d93 commit c9a3d991640539375ba2bf8b6a0669a6c120df6d @jeremy jeremy committed Apr 17, 2009
View
18 activesupport/lib/active_support/core_ext/string/access.rb
@@ -41,17 +41,29 @@ def to(position)
# "hello".first(2) # => "he"
# "hello".first(10) # => "hello"
def first(limit = 1)
- mb_chars[0..(limit - 1)].to_s
+ if limit == 0
+ ''
+ elsif limit >= size
+ self
+ else
+ mb_chars[0...limit].to_s
+ end
end
-
+
# Returns the last character of the string or the last +limit+ characters.
#
# Examples:
# "hello".last # => "o"
# "hello".last(2) # => "lo"
# "hello".last(10) # => "hello"
def last(limit = 1)
- (mb_chars[(-limit)..-1] || self).to_s
+ if limit == 0
+ ''
+ elsif limit >= size
+ self
+ else
+ mb_chars[(-limit)..-1].to_s
+ end
end
end
else
View
2 activesupport/test/core_ext/string_ext_test.rb
@@ -132,10 +132,12 @@ def test_access
assert_equal "h", s.first
assert_equal "he", s.first(2)
+ assert_equal "", s.first(0)
assert_equal "o", s.last
assert_equal "llo", s.last(3)
assert_equal "hello", s.last(10)
+ assert_equal "", s.last(0)
assert_equal 'x', 'x'.first
assert_equal 'x', 'x'.first(4)

0 comments on commit c9a3d99

Please sign in to comment.
Something went wrong with that request. Please try again.