diff options
author | Jeremy Kemper <jeremy@bitsweat.net> | 2009-04-17 13:44:59 -0500 |
---|---|---|
committer | Jeremy Kemper <jeremy@bitsweat.net> | 2009-04-17 13:44:59 -0500 |
commit | 60896ca6f4c89260cb9770487f80dec829674b89 (patch) | |
tree | 7630f84d10ab607dda8c4a57026cf3d75d4d7f82 | |
parent | abb899c54e8777428b7a607774370ba29a5573bd (diff) | |
download | rails-60896ca6f4c89260cb9770487f80dec829674b89.tar.gz rails-60896ca6f4c89260cb9770487f80dec829674b89.tar.bz2 rails-60896ca6f4c89260cb9770487f80dec829674b89.zip |
Clearer String#first and #last edge cases. Fix that foo.first(0) == instead of foo.
-rw-r--r-- | activesupport/lib/active_support/core_ext/string/access.rb | 18 | ||||
-rw-r--r-- | activesupport/test/core_ext/string_ext_test.rb | 2 |
2 files changed, 17 insertions, 3 deletions
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) |