Skip to content

Commit

Permalink
Clearer String#first and #last edge cases. Fix that foo.first(0) == i…
Browse files Browse the repository at this point in the history
…nstead of foo.
  • Loading branch information
jeremy committed Apr 17, 2009
1 parent dc69d93 commit c9a3d99
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
18 changes: 15 additions & 3 deletions activesupport/lib/active_support/core_ext/string/access.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -41,17 +41,29 @@ def to(position)
# "hello".first(2) # => "he" # "hello".first(2) # => "he"
# "hello".first(10) # => "hello" # "hello".first(10) # => "hello"
def first(limit = 1) 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 end

# Returns the last character of the string or the last +limit+ characters. # Returns the last character of the string or the last +limit+ characters.
# #
# Examples: # Examples:
# "hello".last # => "o" # "hello".last # => "o"
# "hello".last(2) # => "lo" # "hello".last(2) # => "lo"
# "hello".last(10) # => "hello" # "hello".last(10) # => "hello"
def last(limit = 1) 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
end end
else else
Expand Down
2 changes: 2 additions & 0 deletions activesupport/test/core_ext/string_ext_test.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -132,10 +132,12 @@ def test_access


assert_equal "h", s.first assert_equal "h", s.first
assert_equal "he", s.first(2) assert_equal "he", s.first(2)
assert_equal "", s.first(0)


assert_equal "o", s.last assert_equal "o", s.last
assert_equal "llo", s.last(3) assert_equal "llo", s.last(3)
assert_equal "hello", s.last(10) assert_equal "hello", s.last(10)
assert_equal "", s.last(0)


assert_equal 'x', 'x'.first assert_equal 'x', 'x'.first
assert_equal 'x', 'x'.first(4) assert_equal 'x', 'x'.first(4)
Expand Down

0 comments on commit c9a3d99

Please sign in to comment.