Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
For 2023 (and 2024 ...) - we are now fully retired from IT training.
We have made many, many friends over 25 years of teaching about Python, Tcl, Perl, PHP, Lua, Java, C and C++ - and MySQL, Linux and Solaris/SunOS too. Our training notes are now very much out of date, but due to upward compatability most of our examples remain operational and even relevant ad you are welcome to make us if them "as seen" and at your own risk.

Lisa and I (Graham) now live in what was our training centre in Melksham - happy to meet with former delegates here - but do check ahead before coming round. We are far from inactive - rather, enjoying the times that we are retired but still healthy enough in mind and body to be active!

I am also active in many other area and still look after a lot of web sites - you can find an index ((here))
String Functions in Ruby

You may have notices that I swapped the case of my string, as an example, in the Here document demonstration. That's just the tip of the iceberg - there are a large number of methods that you can run on Ruby strings.


Operators such as + and * work on strings (concatenate and replicate). The % operator is a short form for sprintf, and the << operator is the same as +. You can treat a character string as an array of characters too.


Currencyformat = "%.2f"

desert = ["Sticky toffee pudding",
        "Rhubarb crumble",
        "Bread and butter pudding",
        "Jam rolly polly",
        "Spotted Dick"]

withon = ["ice cream","cream",

take = desert[rand(desert.length).to_i]
topped = withon[rand(withon.length).to_i]

sweet = take + " and " + topped + "\n"
print "Your desert is #{sweet}"

print "\nA party of 4? ...\n"
print sweet * 4

bill = 7.5
print "Your bill is " + Currencyformat % bill + " today\n"

Note the use of the rand function, used in conjunction with length to choose a random member from an array (and an interesting sweet!). Also note the neat way that we can store a format string in a constant so that we can use it consistently and immutably throughout.

earth-wind-and-fire:~/ruby/r109 grahamellis$ ruby sop.rb
Your desert is Bread and butter pudding and ice cream

A party of 4? ...
Bread and butter pudding and ice cream
Bread and butter pudding and ice cream
Bread and butter pudding and ice cream
Bread and butter pudding and ice cream
Your bill is 7.50 today
earth-wind-and-fire:~/ruby/r109 grahamellis$


To change case:

 capitalize - first character to upper, rest to lower
 downcase - all to lower case
 swapcase - changes the case of all letters
 upcase - all to upper case

To rejustify:

 center - add white space padding to center string
 ljust - pads string, left justified
 rjust - pads string, right justified

To trim:

 chop - remove last character
 chomp - remove trailing line separators
 squeeze - reduces successive equal characters to singles
 strip - deletes leading and trailing white space

To examine:

 count - return a count of matches
 empty? - returns true if empty
 include? - is a specified target string present in the source?
 index - return the position of one string in another
 length or size - return the length of a string
 rindex - returns the last position of one string in another
 slice - returns a partial string

To encode and alter:

 crypt - password encryption
 delete - delete an intersection
 dump - adds extra \ characters to escape specials
 hex - takes string as hex digits and returns number
 next or succ - successive or next string (eg ba -> bb)
 oct - take string as octal digits and returns number
 replace - replace one string with another
 reverse - turns the string around
 slice! - DELETES a partial string and returns the part deleted
 split - returns an array of partial strings exploded at separator
 sum - returns a checksum of the string
 to_f and to_i - return string converted to float and integer
 tr - to map all occurrences of specified char(s) to other char(s)
 tr_s - as tr, then squeeze out resultant duplicates
 unpack - to extract from a string into an array using a template

To iterate:

 each - process each character in turn
 each_line - process each line in a string
 each_byte - process each byte in turn
 upto - iterate through successive strings (see "next" above)

Let's see the sort of thing we can do with those - reading some data on A roads that's saved on the end of a program into a single string object, then stepping through each of the lines one at a time and extracting information from them. In practise, just the sort of thing that you might want to do!

info = DATA.read
footers = {}
info.each_line do |aroad|
        cf = aroad.index('(')
        comment = nil
        if cf != nil
                comment = aroad.slice!(cf,aroad.length)
        number, afrom, ajunk, ato = aroad.split
        print "The #{number} runs from #{afrom.upcase.center(15)} " +
                "to #{ato}\n"
        footers[number] = comment.tr("()","[]") if comment
p footers

A1 London to Edinburgh (The Great North Road)
A2 London to Dover (Watling Street)
A3 London to Portsmouth (Portsmouth Road)
A4 London to Bristol (The Great West Road, or Bath Road)
A5 London to Holyhead (Watling Street)
A6 Luton to Carlisle (The A6 splits off from the A5 at St.
Albans - though the A6 as numbered today starts at Luton)
A7 Edinburgh to Carlisle
A8 Edinburgh to Greenock
A9 Edinburgh to Thurso

And here's the sort of output that produces:

earth-wind-and-fire:~/ruby/r109 grahamellis$ ruby stdo.rb
The A1 runs from LONDON to Edinburgh
The A2 runs from LONDON to Dover
The A3 runs from LONDON to Portsmouth
The A4 runs from LONDON to Bristol
The A5 runs from LONDON to Holyhead
The A6 runs from LUTON to Carlisle
The A7 runs from EDINBURGH to Carlisle
The A8 runs from EDINBURGH to Greenock
The A9 runs from EDINBURGH to Thurso
{"A1"=>"[The Great North Road]\n",
"A2"=>"[Watling Street]\n",
"A3"=>"[Portsmouth Road]\n",
"A4"=>"[The Great West Road, or Bath Road]\n",
"A5"=>"[Watling Street]\n",
"A6"=>"[The A6 splits off from the A5 at St. Albans -
though the A6 as numbered today starts at Luton]\n"}
earth-wind-and-fire:~/ruby/r109 grahamellis$

See also Training Courses in Ruby

Please note that articles in this section of our web site were current and correct to the best of our ability when published, but by the nature of our business may go out of date quite quickly. The quoting of a price, contract term or any other information in this area of our website is NOT an offer to supply now on those terms - please check back via our main web site

Related Material

Ruby - Strings and Regular Expressions
  [970] - ()
  [986] - ()
  [987] - ()
  [1195] - ()
  [1305] - ()
  [1588] - ()
  [1875] - ()
  [1887] - ()
  [1891] - ()
  [2293] - ()
  [2295] - ()
  [2608] - ()
  [2614] - ()
  [2621] - ()
  [2623] - ()
  [2980] - ()
  [3424] - ()
  [3621] - ()
  [3757] - ()
  [3758] - ()
  [4388] - ()
  [4505] - ()
  [4549] - ()

resource index - Ruby
Solutions centre home page

You'll find shorter technical items at The Horse's Mouth and delegate's questions answered at the Opentalk forum.

At Well House Consultants, we provide training courses on subjects such as Ruby, Lua, Perl, Python, Linux, C, C++, Tcl/Tk, Tomcat, PHP and MySQL. We're asked (and answer) many questions, and answers to those which are of general interest are published in this area of our site.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2024: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/solutions/ruby-str ... -ruby.html • PAGE BUILT: Wed Mar 28 07:47:11 2012 • BUILD SYSTEM: wizard