Learning Ruby -- Lesson 4: Variables, User Input and Type Conversion
So, upto this point, we have only been working with literal values. A literal value, is a static value; hardcoded by the programmer. For example:
1 2 10.5 "String"
are all literals.
But, what if you aren't sure what the final value should be? Or if the value is chosen by the user? Well, as you may know, we have variables to do that. Variables are the programmers direct access to a computer's memory (RAM). Any object can be stored in variables for later use, or for whatever reason storing an object in memory may be.
Anyways, let's try it on for size:
irb(main):001:0> variable = 10 => 10 irb(main):002:0> puts variable 10 => nil
Yup, it's almost that simple.
variable_name = value
value can be anything from a literal value to a method that returns a value to even another variable.
Now, that was the simple part. The not so simple part (but still quite simple) are variable naming rules.
variables, by rule, MUST start with a lowercase letter or underscore, and can contain letters, numbers and underscores. Also, you should know that variables cannot share the same name as ANY ruby keyword or reserved word. Ruby keywords are as follows:
alias and BEGIN begin break case class def defined? do else elsif END end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield
there are some exceptions to these rules, however to avoid confusion, we will go over these exceptions later. (There are however, NO exceptions to using keywords as variable names)
Another thing that you should know about variables, is that although you can name a variable anything you would like; it is much better practice to give variables distinct, meaningful names. This however, is called coding convention--it is not necessary to run a program correctly, however it makes the code MUCH easier to read, and so you don't forget what each variable is later down the road.
Another coding convention, is the style we use to write out our variables. The two most popular types are camel casing and snake casing.
A camel-cased variable name would begin with a lowercase letter, and any sequential words begin with a capital:
thisIsACamelCasedVariableName = nil
A snake-cased variable name (which you will find much more popular in the ruby community) Snake casing means each word is separated by an underscore `_`:
this_is_a_snake_cased_variable_name = nil
Whichever way you prefer is upto you. I personally find snake casing easier to read, and all my lessons will reflect that convention. Note that it is good practice to choose a neat and consistent style.
Now, back to the actual coding. So, you should understand the basic concept of what an object is, but what does this mean for programming?
Well, as I said, everything is an object in ruby. To use an object, we must first create an instance of an object type. Whenever you store something in a variable, you are essentially storing an instance of an object in memory to be called upon and used. So, let's look at this example:
variable = 10
What we are doing here, is creating an instance of the Fixnum object (which is an integer type), which is initialized to have the value 10, and storing it into the variable called `variable.` This means, you can now call any method or function belonging to the Fixnum object.
irb(main):001:0> variable = 10 => 10 irb(main):002:0> variable.to_s => "10"
Whoa, what happened here? What I have done here, is called the `to_s` method from variable. To call methods/attributes from a variable (or any instance of an object) in ruby, we use what is called "dot notation" object_instance dot method/attribute name. The method then returns a value (as defined by the method, in this case a string). What I mean by the method "returning a value" is that whenever a line of code is executed it sends back a value to the program. In this case, we didn't do anything with that value, but if we wanted to, we could store that value in another variable:
other_variable = variable.to_s
and in case you were wondering, to_s is simply a method that returns a string representation of the object that to_s was called from (all objects have this method) (to_s means "to string")
The concept of converting objects in Ruby is called coercing.
There are many different methods for converting data types, one more I will teach you, is the to_i method.
irb(main):001 > "5".to_i => 5 irb(main):002 > "5".to_i + 10 => 15 irb(main):003 > "hello".to_i => 0
The to_i method attempts to convert the object to an integer. In this case, an integer is extracted from a string.
Alright, with that said let's make our first script!
Open up a command prompt, and create a folder for our scripts:
Windows:
C:\> mkdir learnruby C:\> cd learnruby C:\> notepad hello.rb
Linux:
~$ mkdir learnruby ~$ cd learnruby ~$ vi hello.rb
Of course, you can use any text editor that you like, it just so happens that these two editors ship with windows/linux.
Now, enter this code:
# The obligatory Hello, world program puts("Hello, world!")
Now, let's test it out. Save the code, head back to the prompt/terminal and enter:
ruby hello.rb
This invokes the ruby interpreter on `hello.rb` (The script we made)
If everything went well we should see:
ruby hello.rb Hello, world!
As you should know, puts writes text to the screen (or standard output)
# The obligatory Hello, world program
This however, is a comment. Any line preceded by a pound sign `#` will be ignored by the interpreter. Comments are like little signs to either help you or other programmers understand what you are doing.
For long comments, you can do a `block comment`
=begin Anything between the begin and end is one large comment =end
Alright, well that was fairly anti-climatic. Let's make this program a little more interesting.
Let's make a greeting program, that will take the user's name, then display a personalized greeting.
First, I will teach you how to get input from the user.
gets
gets is a function that, when called, gets a string from the standard input (from the user).
# First we will need to get a name from the user # We should store that name in a variable, for later use name = gets
gets always returns a string, so we can take that value and store it in a variable.
Now, that we have the name, we need to display the greeting. There are a couple of ways we can do this.
The first way: concatenating strings
If you remember, earlier we tried adding strings together:
"Hello," + " World!"
This is called concatenation, and it works the same way with variables that hold a string:
"Hello, " + name + "!"
And of course, we can pass that to puts:
# Display our personalized greeting puts("Hello, " + name + "!")
Another way we can do this is:
"Hello, #{name}!"
This is called embedded expressions. This tells the interpreter to take the value of the expression within the `#{}` and call its to_s method and place it within the string. You can use any kind of expression, such as addition, subtraction and even call methods from within those tags. It is important however, to know that the `#{}` is only available in strings defined with the double-quotes `""`, strings defined with single-quotes `''` will interpret the #{name} literally and display #{name}.
So, this will be our new hello.rb script:
# Prompt the user for input puts("Please enter your name:") # Get user's name name = gets # Display personalized greeting puts("Hello, #{name}!")
Alright, let's call the ruby interpreter on this script again:
ruby hello.rb Please enter you name: kellessdee Hello, kellessdee !
Wait a minute, why is that explanation mark on a different line than the greeting?
Well, allow me to explain. Like its counterpart `puts`, which prints a new-line after the string, gets also reads in the new line character. So how do we get rid of it?
The simplest way, would be to invoke the "strip" method on the string:
puts("Hello, #{name.strip}")
Now lets try it:
ruby hello.rb Please enter you name: kellessdee Hello, kellessdee!
Ah, much better.
We are almost finished with this lesson. This was probably a lot more to take in than the previous lessons, so let it soak in, play around with everything I have given you.
Before I let you go however, I would like to mention a few other things:
I was talking about a "new-line character" earlier, now you may not have gave it much thought, but I would like to point this out. With computers, to represent certain characters (such as backspaces, tabs, returns, etc) it uses a different kind of symbol. For example, the New-line escape character is:
"\n"
If you put this in a puts,
irb(main):001 > puts "Hello,\nWorld!" Hello, World! => nil
you can see that the interpreter puts the rest of the string on a new line. This can be useful when, say, building a long multi-line string, etc.
Other escape characters include:
\t tab \s space \b backspace \\ backslash \" double quote \' single quote (only used within single-quote strings)
It is important to note, that like the `#{}` escape characters only work within `""` (except for the case of `\'`) strings. In `''` strings, they will be interpreted literally. I suggest you test this out, to see what I mean.
Coding Challenge:
1. Write a script, that takes two numbers from the users, and performs some kind of mathematic operation on them.
2. Write a script, that takes the users first and last name, and creates an e-mail address for them, in the format:
lastname.firstname@pretendwebsite.extension
firstname should be the user's inputted first name
lastname should be the user's inputted last name
pretendwebsite.extension can be any website name you wish
Last, but not least:
If you wish to learn more about the avaible objects and methods ruby provides, visit:
http://www.ruby-doc.org/core-1.9.3/
This is the english documentation for the ruby api. Here it describes all of ruby's built-in objects and describes all of their methods. Please note that "classes" are a term for objects that can be created. If you don't know what that means, do not worry for now, I will explain that later. For now, you should explore the String class and the Numeric class. It will give you all the actions that can be performed on those objects, and it will give you a feel for the ruby documentation. I promise, one day it will be your best friend.
Finally, don't let me stop you from learning from other places on your own if you wish to do so. In fact, if you really want to learn ruby, I ENCOURAGE you to do so.
1.9.2p290 :001 > p "hello" "hello" => "hello"
This is the p method. This method calls the `inspect` method of the object (in this case "hello") and prints it to the console. It also appends a new-line character to the string.
1.9.2p290 :002 > print "hello" hello => nil
This is the print method. This method will print the object, and if it is not a string, call the `to_s` method from the object. This method does not append any new lines.
1.9.2p290 :006 > printf "hello" hello => nil
This method is the printf (print formatted) method. It can be used to format your output. I will explain this method in more detail later. (feel free to look it up)
irb(main):003 > puts "hello" hello => nil
Puts works exactly like print, except it appends a new line character. You can also specify multiple objects:
irb(main):011 > puts "hello", "world" hello world => nil
irb(main):004 > putc "hello" h => "hello" irb(main):005 > putc "h" h => "h" irb(main):009 > putc "A" A => "A" irb(main):010 > putc 65 A => 65
Putc essentially means put character. It reads the first character (or byte/numeric value) and prints it as a character.
I hope that clears things up. I am not sure how their functionality works in rpg maker xp, however p works well.
The exclamation, or bang, is a convention on ruby signifying that the method modify's the caller.
For example,
irb(main):001 > str = "hello \n" => "hello \n"
Here we make a string with some whitespace
irb(main):002 > print str.strip hello => nil
Here we print the string without whitespace
irb(main):003 > str => "hello \n"
str has not changed
irb(main):004 > print str.strip! hello => nil
here we print the string without whitespace again
irb(main):005 > str => "hello"
this time, str no longer has any whitespace.
So, when you see a method with a `!` at the end, it usually means that the method in question modifies the object that called the method.
0 Comments
Recommended Comments
There are no comments to display.
Please sign in to comment
You will be able to leave a comment after signing in
Sign In Now