Getting the Parts of a String You Want

Problem

You want only certain pieces of a string.

Solution

To get a substring of a string, call its slice method, or use the array index operator (that is, call the [] method). Either method accepts a Range describing which characters to retrieve, or two Fixnum arguments: the index at which to start, and the length of the substring to be extracted.

	s = 'My kingdom for a string!'
	s. 
slice(3,7) # => "kingdom"
	s[3,7] # => "kingdom"
	s[0,3] # => "My "
	s[11, 5] # => "for a"
	s[11, 17] # => "for a string!"

To get the first portion of a string that matches a regular expression, pass the regular expression into slice or []:

	s[/.ing/] # => "king"
	s[/str.*/] # => "string!"

 

Discussion

To access a specific byte of a string as a Fixnum, pass only one argument (the zerobased index of the character) into String#slice or [] method. To access a specific byte as a single-character string, pass in its index and the number 1.

	s.slice(3) # => 107
	s[3] # => 107
	107.chr # => "k"
	s.slice(3,1) # => "k"
	s[3,1] # => "k"

To count from the end of the string instead of the beginning, use negative indexes:

	s.slice(-7,3) # => "str"
	s[-7,6] # => "string"

If the length of your proposed substring exceeds the length of the string, slice or [] will return the entire string after that point. This leads to a simple shortcut for getting the rightmost portion of a string:

	s[15…s.length] # => "a string!"

 

See Also

  • Recipe 1.9, "Processing a String One Word at a Time"
  • Recipe 1.17, "Matching Strings with Regular Expressions"


Strings

Numbers

Date and Time

Arrays

Hashes

Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming

XML and HTML

Graphics and Other File Formats

Databases and Persistence

Internet Services

Web Development Ruby on Rails

Web Services and Distributed Programming

Testing, Debugging, Optimizing, and Documenting

Packaging and Distributing Software

Automating Tasks with Rake

Multitasking and Multithreading

User Interface

Extending Ruby with Other Languages

System Administration



Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399

Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net