Ruby for the Newbie - Constants
(Page 4 of 4 )
Change is the one true constant. I never have bills, only change. It never changes. Ha ha. Seriously, constants in Ruby are similar to variables, except that they hold values you don't expect to change. This is different from most programming languages, where constants don't change.
Unlike variables, the first letter of a constant must be uppercase (it's best just to make the whole name uppercase).
Declaring a constant is the same as declaring a variable:
SOCIAL= "193-12-1045"
SOCIAL_SECURITY= "888-88-8888"
Although you will get a warning message each time you change a constant, you can still do so:
SOCIAL= "111-11-1111"
This will result in a message that your file constants have already been initialized.
However, the value will still be changed.
Gathering Data from the User
Sometimes you need to gather data from a user. Say you want to rob them blind. You would have to have them give you their pin number. You might also want to taunt them. I mean what good is stealing someone's money if you can't mock them afterwards?
To do this, you will use the gets method.
print "What is your pin number?"
gets
chomp
puts "I R LEET. I HAV UR PIN #($_)!"
You might notice a few new things in that code. As I said before, the gets method retrieves the data the user inputs, including the enter key they press to send the data. This value plus the enter key is stored in a default variable, $_. To get rid of the enter key, we use the chomp method. Finally, we print the final sentence, inserting the value of our variable (the pin number in this instance) into the sentence. Resulting in:
"What is your pin number?"
"I R LEET. I HAVE UR PIN # (whatever value the user put in) !"
That concludes this portion of the Ruby beginner's tutorial. In the next part, we will work with operators, arrays, and conditionals. See you then.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |