Data is placed in containers called variables. As their name suggests, you can change the value in these containers. Ruby has several variable types. We will use the local variable type.
The first step is to name your variables. Variable names should be short and descriptive, and avoid special characters unless specially required. Local variables should start with a lower case letter or a “_” symbol. Acceptable names can include just letters or a combination of letters and numbers, such as “income”, “_income”, “a”, “i”, “a1”, or “a2”.
Each variable has a data type. Ruby will attempt to figure out the property data type for a variable, but you can provide Ruby with hints to avoid mistakes.
Here are some of the Ruby data types:
- Integer—integer numbers, such as – 3, -2, -1, 0, 1, 2, or 3.
- Float—floating or decimal numbers such as -89.02887, 0.0, 3.14, or 98733484.2
- String—text, such as Sam, Jean, or Mary, or A, B, or C.
There are other data types, but the ones above are sufficient for our present purposes.
We can set initial values for our variables; the data type will be shown as a comment. Anything after the “#” symbol on a line is treated as a nonfunctional comment.
# INTEREST INCOME CALCULATOR # Goal: to calculate interest income. # Data and information types and initialize parameters # Initial sum of money which is a number income = 0.0 # Float # Interest rate which is a number time = 0 # Integer # Calculate and Display Results while time
Income shall be a float, since we may need to use fractional amounts of currency. We tell Ruby that income is a float variable by adding a decimal point with an extra 0 afterwards. Otherwise, Ruby will guess this is an integer variable, which would cut off anything after the decimal point. Each unit of time shall be a discrete amount. So the variable time is an integer.
« Ruby Programming, Pseudocode and Comments | COURSE | Operators and Simple Math »