Introduction To Ruby
String Handling
As with any programming language, Ruby has methods and statements that assist with processing information that is stored as a string of characters.
Characters & Substrings
The example shows how you can access and assign values to the parts of a string.
# Characters & Substrings
the_string = "some text"
puts "The string: #{the_string}"
a = the_string.length
puts "#{a} characters in the string"
print "\nFirst character: "
print the_string[0]
print "\n"
print "Last character: "
print the_string[-1]
print "\n"
print "Last but one character: "
print the_string[-2]
print "\n"
print "Change last character: "
the_string[-1] = "T"
puts "The string: #{the_string}"
print "First 4 characters: "
print the_string[0,4]
print "\n"
print "Characters 3 - 7: "
print the_string[2..6]
print "\n"
gets
Iteration With Strings
You can use Ruby's iteration structures to access all elements within a string.
# Strings
the_string = "some text"
puts "The string: #{the_string}"
# using each_char
the_string.each_char {|a| puts a}
# using a for in loop
for x in 0..the_string.length do
puts the_string[x]
end
gets
String Methods
The example demonstrates some of the things you can do with a string. Where there is an exclamation mark at the end of a method, that means that the method changes the string. If you don't want to change the original string, leave out the exclamation mark and assign the value to another variable. This has been done with the reverse example.
# Strings
the_string = "some text"
puts "The string: #{the_string}"
# Convert to sentence case
the_string.capitalize!
puts "The string: #{the_string}"
# Toggle cases
the_string.swapcase!
puts "The string: #{the_string}"
# Convert to lower case
the_string.downcase!
puts "The string: #{the_string}"
# Convert to upper case
the_string.upcase!
puts "The string: #{the_string}"
# Includes?
if the_string.include? "ME" then
puts "String includes 'ME'"
end
# Reverse
a = the_string.reverse
puts "Reversed: #{a}"
gets
Challenge
The best challenge to undertake for working with strings is to make a simple hangman program. There is a fair amount to plan for such a task. You can replace the pictures of the hanged man by simply having a limited number of incorrect guesses. You should display the word on screen using a * for the letters. When a correct letter is guessed, you display the word showing the correctly guessed letters in place, asterisks for the ones that haven't been guessed yet.