How to use the concept of String Building
A brief description: String Building involves the careful preparation of strings to be used elsewhere in the program. Typically this takes the form of manipulating a string to be used with a puts statement.
Say you have a puts statement. We all know that puts adds a hard return (new line) at the end, so two puts back to back will print on different lines. There are ways to stop puts from doing that, but it’s typically more clear to simply avoid the problem. Say also that the reason you want to use different lines is because you are printing something that takes a lot of space to calculate. It can also be used to build single lines of repeating patterns.
Let’s use a rather contrived example:
Once upon a time, a user entered in a number. The user wanted a single line that had that number of “X”s, followed by the same number of underscores, followed by 1 less X, and so on.
We all know how to calculate how many of what items they want, and it would look like this:
n = gets.to_i while n > 0 puts 'X'*n puts '_'*n n = n-1 end
The problem is, that’s on a lot of lines. A simple change to use String Building fixes that, and gives the user what they really wanted.
n = gets.to_i str = '' while n > 0 str = str + 'X'*n str = str + '_'*n n = n-1 end puts str
This is 1 more line than the original, but it removes all of the new lines that puts enters.
Again, this is a rather contrived example, but string building has its benefits:
It’s easy to read. Even though there might be shorter, better solutions for the problem described. String building is very easy to read. A programming coming back to this code will know exactly what’s going on.
It’s easy to write. The concept is fairly simple, and it’s very easy to apply. As you see in the example above, we just changed “puts” to “string = string +” and now we use string building.
All in all, String Building is a useful tool that helps with a lot of different problems (like lab 7!)
Leave a comment
You must be logged in to post a comment.