Sha256: 033e4bf95da8b53cd3d853c9774e1ae5905a37c0049d4e9b825614386b693ea0
Contents?: true
Size: 1.44 KB
Versions: 3
Compression:
Stored size: 1.44 KB
Contents
class String # Returns first _n_ separations, where separator is # either nil, a String or a Regexp. If a zero-length # record separator is supplied then the string is # split on each character. This is the default. # If the record separator is set to <tt>nil</tt>, # then the string is split on white spaces (/\s+|\Z/). # If the record separator is set to <tt>"\n"</tt>, # then the string is split on lines (/\n+|\Z/). # # require 'facet/string/first' # # "Hello World".first(3) #=> "Hel" # #-- # Should the default pattern be $/ or $; instead? #++ def first(n=1, pattern='') pattern = '' if pattern == // case pattern when '' return slice(0,n) when "\n" pattern = /\n+|\Z/ when nil pattern = /\s+|\Z/ when String pattern = Regexp.new( Regexp.escape( separator ) ) #if String === separator end i,s,e = 0,0,0 n.times { i = self.index( pattern, s ) break unless i e = i s = $~.end(0) } slice(0...e) end end #__TEST__ if __FILE__ == $0 require 'test/unit' class TestCase < Test::Unit::TestCase def test_first assert_equal( "Hel", "Hello World!".first(3) ) assert_equal( "Hel", "Hello World!".first(3, //) ) assert_equal( "Hello", "Hello World!".first(1, nil) ) assert_equal( "Hello", "Hello\nWorld!".first(1, "\n") ) assert_equal( "Hello\nWorld!", "Hello\nWorld!".first(2, "\n") ) end end end
Version data entries
3 entries across 3 versions & 1 rubygems
Version | Path |
---|---|
facets-0.7.1 | lib/facet/string/first.rb |
facets-0.7.0 | lib/facet/string/first.rb |
facets-0.7.2 | lib/facet/string/first.rb |