Home > Articles > Programming > Ruby

📄 Contents

  • Print
  • + Share This
This chapter is from the book

2.33 Generating Successive Strings

On rare occasions we may want to find the "successor" value for a string; for example, the successor for "aaa" is "aab" (then "aad", "aae", and so on).

Ruby provides the method succ for this purpose:

droid = "R2D2"
improved  = droid.succ         # "R2D3"
pill  = "Vitamin B"
pill2 = pill.succ              # "Vitamin C"

We don't recommend the use of this feature unless the values are predictable and reasonable. If you start with a string that is esoteric enough, you will eventually get strange and surprising results.

There is also an upto method that applies succ repeatedly in a loop until the desired final value is reached:

"Files, A".upto "Files, X" do |letter|
  puts "Opening: #{letter}"

# Produces 24 lines of output

Again, we stress that this is not used frequently, and you use it at your own risk. Also we want to point out that there is no corresponding "predecessor" function at the time of this writing.

  • + Share This
  • 🔖 Save To Your Account