From 60896ca6f4c89260cb9770487f80dec829674b89 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 17 Apr 2009 13:44:59 -0500 Subject: Clearer String#first and #last edge cases. Fix that foo.first(0) == instead of foo. --- .../lib/active_support/core_ext/string/access.rb | 18 +++++++++++++++--- activesupport/test/core_ext/string_ext_test.rb | 2 ++ 2 files changed, 17 insertions(+), 3 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/string/access.rb b/activesupport/lib/active_support/core_ext/string/access.rb index 7fb21fa4dd..e067f930da 100644 --- a/activesupport/lib/active_support/core_ext/string/access.rb +++ b/activesupport/lib/active_support/core_ext/string/access.rb @@ -41,9 +41,15 @@ module ActiveSupport #:nodoc: # "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: @@ -51,7 +57,13 @@ module ActiveSupport #:nodoc: # "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 diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 6c9b7e7236..7d51e81feb 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -132,10 +132,12 @@ class StringInflectionsTest < Test::Unit::TestCase 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) -- cgit v1.2.3