Method: PlainText#head
- Defined in:
- lib/plain_text.rb
#head(num_in = DEF_HEADTAIL_N_LINES, unit: :line, inclusive: true, padding: 0, linebreak: $/) ⇒ String
Returns the first num lines (or characters, bytes) or before the last n-th line.
If “byte” is specified as the return unit, the encoding is the same as self, though the encoding for the returned String may not be valid anymore. Note that it is probably the better practice to use string[ 0..5 ] and string#byteslice(0,5) instead of this method for the units of “char” and “byte”, respectively.
For num, a negative number means counting from the last (e.g., -1 (lines, if unit is :line) means everything but the last 1 line, and -5 means everything but the last 5 lines), whereas 0 is forbidden. If a too big negative number is given, such as -9 for String of 2 lines, a null string is returned.
If unit is :line, num can be Regexp, in which case the string of the lines up to the first line that matches the given Regexp is returned, where the process is based on the lines. For example, if num is /ABC/ (Regexp), String of the lines from the beginning up to the line that contains the character “ABC” is returned.
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 |
# File 'lib/plain_text.rb', line 598 def head(num_in=DEF_HEADTAIL_N_LINES, unit: :line, inclusive: true, padding: 0, linebreak: $/) if num_in.class.method_defined? :to_int num = num_in.to_int raise ArgumentError, "Non-positive num (#{num_in}) is given in #{__method__}" if num.to_int < 1 elsif num_in.class.method_defined? :named_captures re_in = num_in else raise raise_typeerror(num_in, 'Integer or Range') end case unit when :line, "-n" # Regexp (for boundary) return head_regexp(re_in, inclusive: inclusive, padding: padding, linebreak: linebreak) if re_in # Integer (a number of lines) ret = split(linebreak, -1)[0..(num-1)].join(linebreak) # -1 is specified to preserve the last linebreak(s). return ret if size <= ret.size # Specified line is larger than the original or the last NL is missing. return(ret << linebreak) # NL is added to the tail as in the original. when :char return self[0..(num-1)] when :byte, "-c" return self.byteslice(0..(num-1)) else raise ArgumentError, "Specified unit (#{unit}.inspect) is invalid in #{__method__}" end end |