Welcome to little random thoughts of Ruby... My topic tonight is about the prompt snippet I gave yesterday. I didn't realize it, as often happens, but it was so simple, I had to add the feature.
I realized while writing another wrapper for benchmark and profiler, that it is pretty common to add chomp() to our gets. But there may be times when we want what gets, um... well, gets. (Who am I to assume what you may want?) So I give an option. I default to a plain old string that is stripped. But you can easily get the true gets result by asking for true results. Can you guess that the flag to get it could be 'true'?

In my irb, Here are a couple of examples...
>> 'Please type something: '.prompt
Please type something: Something
=> "Something"
>> 'Please type something (This will not be stripped): '.prompt(true)
Please type something (This will not be stripped): Something
=> "Something\n
Well, I thought it was pretty cool.
3 comments:
Well Victor, if yesterday evening's sundown would have been a bit more into yellow, and had gone easy on the red, it could have made me happy (freely after sth. Paul Lutus has written).
But now there is the no_chomp option. I like all kinds of configurability. Making the default optional should become a pattern. ;-)
Victor, this is indeed a very helpful method, and to have the possibility to pass an option is really great. But I would suggest to rename the "no-chomp = false" option into "chomp = true" for better readability.
And remember JLH and his holy TERNARY OPERATOR. :)
I do agree with the readability for sure.
def prompt(without_chomp = false)
print self
STDOUT.flush unless STDOUT.sync
without_chomp ? gets : gets.chomp
end
It is so much clearer this way.
The logic for the false default value is that it is so much easier to use almost anything else to flag a true result for the decision, but you only have two options to bring a 'false' result. How this may be used is left to someone else's imagination.
This leaves the last reason... If I can make the use of the code 'positive' to gain features that may be wanted, rather than having the user concentrate on 'negatives', then it makes the experience that much more positive all around. (In other words, if this were a hidden library, the user would only see the positive...) But that may be a whole other blog on the "Positive Karma of Ruby Programming"
Post a Comment