您的位置:首页 > 编程语言 > Ruby

Programming in the Ruby language

2005-09-12 13:14 555 查看


developerWorks > Linux | Open source projects >


Programming in the Ruby language

Introducing Ruby variables, quotes, arrays, objects, and methods




Document options
<!--
document.write('<tr valign="top"><td width="8"><img src="//www.ibm.com/i/c.gif" width="8" height="1" alt=""/></td><td width="16"><img alt="Set printer orientation to landscape mode" height="16" src="//www.ibm.com/i/v14/icons/printer.gif" width="16" vspace="3" /></td><td width="122"><p><b><a class="smallplainlink" href="javascript:print()">Print this page</a></b></p></td></tr>');
//-->
<!--
document.write('<tr valign="top"><td width="8"><img src="//www.ibm.com/i/c.gif" width="8" height="1" alt=""/></td><td width="16"><img src="//www.ibm.com/i/v14/icons/em.gif" height="16" width="16" vspace="3" alt="Email this page" /></td><td width="122"><p><a class="smallplainlink" href="javascript:void newWindow()"><b>E-mail this page</b></a></p></td></tr>');
//-->


Print this page


E-mail this page
Rate this page


Help us improve this content
Level: Intermediate
Joshua Drake (jd@commandprompt.com), Project Manager, Command Prompt, Inc.

01 Jul 2001
This first article of a four-part series is an introduction to Ruby programming by Joshua Drake, author of the Linux Networking HOWTO, Linux PPP HOWTO, and Linux Consultants HOWTO, and co-founder of the Linux custom development company Command Prompt, Inc. Readers who know how to use some other scripting language, such as Perl, will benefit most from this series. Joshua begins his exploration into Ruby with a discussion of variables, quotes, arrays, objects, and methods. Subsequent articles in this Ruby series will deal with more advanced topics, including developing graphical applications and using Ruby with databases.Ruby, by way of an introduction, is a pure object-oriented scripting language, developed by Yukihiro Matsumoto in Japan. It was primarily designed to handle text processing and systems management tasks.
As the example below shows, the Ruby syntax will be familiar to anyone who has written in a scripting language such as Perl or PHP. However, unlike Perl or PHP, which require the use of a semi-colon as a line terminator, Ruby requires no line termination. Some developers may at first find themselves a little confused by this, but I find that it actually speeds up development. For example, I don't get the message, "Error missing ; on line x" anymore. For a quick first glance into the world of Ruby, and to illustrate this idea, take a look at the classic Hello World example:

Listing 1. Hello world
#!/usr/bin/ruby
#
# My first ruby program
#
print "Hello World/n"



Back to top
Variables
Variables in Ruby are very easy to deal with. Let's expand our first example and include a simple method of changing the output.

Listing 2. Changing the output
#!/usr/bin/ruby
#
# My first ruby program
#

# Declare our salutation

$salut = "Good Bye World/n"

# Prepare statements

print "Hello World/n"
print $salut
Using the
$salut
variable, we can easily change the output of the second
print
statement at any time. You can declare variables at any point in your program.

Listing 3. Declaring variables
#!/usr/bin/ruby
#
# My first ruby program
#

$salut = "Good Bye World/n"

print "Hello World/n"
print $salut

#
# Declare a new value for $salut.
#

$salut = "Oh, I am sorry. I didn't mean to warn
you.../n"

print "What do you mean Good Bye World?/n"
print $salut
If you were to execute the above example, it would output the following:
Hello World
Good Bye World
What do you mean Good Bye World?
Oh, I am sorry. I didn't mean to warn you...
As you can see, the variable re-assignment worked.




Back to top
Quotes, singles and doubles
As do most languages, Ruby differentiates between double quotes and single quotes. In Ruby, the double quote signifies that Ruby is to interpret whatever values are within the quote. For example:
print "Hello World/n"
The Ruby interpreter will not escape the /n and will instead print a new line to STDOUT (Standard Out). However, if we were to execute the same statement with single quotes, like so:
print 'Hello World/n'
Ruby would output the following:
Hello World/n
Notice that a new line was not printed. Ruby instead considered the entire statement to be literal, which is the same functionality Perl uses.




Back to top
Word math
In Ruby, all strings can use operators. This means that we can, in a sense, use math on words. For example:
$salut = $salut * 3
will result in the following:
Oh, I am sorry. I didn't mean to warn you...
Oh, I am sorry. I didn't mean to warn you...
Oh, I am sorry. I didn't mean to warn you...
And
$salut = $salut + " 10, 9, 8..."

print $salut
will result in the following:
Oh, I am sorry. I didn't mean to warn you...
Oh, I am sorry. I didn't mean to warn you...
Oh, I am sorry. I didn't mean to warn you...
10, 9, 8...
Notice that although our variable printed three times, the concatenation of "10, 9, 8..." only printed once at the end of the program. Why is that?
The reason is that we just added "10, 9, 8..." on to the end of our variable. We did not ask for our variable to add "10, 9, 8..." to each line. Also, it is important to notice the inheritance with our current use of variables.
Once a variable is assigned, that variable is static unless reassigned again, as illustrated when we changed
$salut
to equal
"What do you mean Good Bye World? /n"
from
"Hello World/n"
. However, this is not the case when multipliers or concatenation are used with variables. As you can see from the last example, using concatenation (the + sign) with a variable will cause that variable to inherit the previous assignment of the variable plus the string that is added to the assignment of the variable. In our case, " 10, 9, 8..."




Back to top
Arrays
What if you knew that you were going to reassign the
$salut
variable multiple times? In many cases, this will occur. Therefore, instead of manually reassigning the variable, you can put all of the variable values into an array.
An array allows each value of the variables to be addressed separately. Take the following example:
$salut = ['Hello World','Good Bye World','What do you
mean Good Bye World?']

print $salut
The resulting output of the above will look like this:
Hello WorldGood Bye WorldWhat do you mean Good Bye
World?
Obviously, that is not the desired output. There are no spaces or new lines. Therefore, we can identify which part of the array we want to display and use the concatenation techniques we explained earlier to present a readable output.
$salut = ['Hello World','Good Bye World','What do you
mean Good Bye World?']

print $salut[0] + "/n"print $salut[1] + "/n"
print $salut[2] + "/n"
This will result in the following output:
Hello World
Good Bye World
What do you mean Good Bye World?
Let's dissect this code a bit. If we review the array we built:
$salut = ['Hello World','Good Bye World','What do you
mean Good Bye World?']
We are telling Ruby to define a variable called
salut
that has the values of:
$salut = 0 1 2
Hello World Good Bye World What do you mean Good Bye World?
Each value is identified by a number. The number is defined by the number position within the array. The positions always start with 0 and increment from there. So to print the second value in the array, you would type:
print $salut[1]
The easiest thing to forget is that the fields start with 0, not with 1.




Back to top
Conditions -- IF, ELSE
We have explored the basics of presenting data with Ruby. Now let's look at the beginnings of logic within a Ruby program. That is, let's instruct a Ruby program to perform basic functions based on the results it receives from the programmer. We will also look at how to perform conditions on results that a Ruby program receives from a user. New code will be used for these examples.

Listing 4. Performing basic functions based on results
$salut = ['Hello World','Good Bye World','What do you
mean Good Bye World?']

print "When you enter the world, what do you say? "while enterWorld = STDIN.gets enterWorld.chop!if enterWorld == $salut[0]
print "/n" + "Yes. Hello World would be
polite./n"
break
else
print "You say '", enterWorld, "'?!/n" + "You
humans are so rude!/n"
end
end
Several new aspects of Ruby development were introduced with the above snippet of code, so let's walk through it.

A step-by-step walk through our example

#!/usr/bin/ruby
#
# My first interactive ruby script
#

# Define our main variable with an array
$salut = ['Hello World','Good Bye World','What do you mean Good Bye World?']

# Print my first question

print "When you enter the world, what do you say? "

# Create a while loop with the object enterWorld and
await data from
# standard input. The while loop will make sure that
ruby continues
# to process the application until the program tells
it to stop.

while enterWorld = STDIN.gets

# Make sure we use the chop method on the enterWorld
object. The use
# of the chop method will insure that we strip new
lines and carriage
# returns from our input.

# You will notice that using the chop method has an
extra
# character. The ! allows the existing object to be
modified
# by the method. If you did not use the !, you would
have to redeclare
# the enterWorld object for the if condition to
correctly occur.

enterWorld.chop!

# Begin the condition sequence. Basically, if
enterworld equals
# Hello World, which is 0, within the array, print
# a new line. Then print, "Yes, Hello World would be
polite." to the screen.
if enterWorld == $salut[0]
print "/n" + "Yes. Hello World would be
polite./n"

# The break statement tells ruby to stop executing if
the previous
# condition is met. If we did not include this in our
while loop,
# the program would run continuously.

break

# The else statement is used as the secondary
condition. In other
# words, if the first condition is not met, please do
the following.

else
print "You say '", enterWorld, "'?!/n" + "You
humans are so rude!/n"
break

# The end statement is used to close a condition or
loop. In our case,
# it is being used to close both. We are first closing
our if
# condition statements and then stopping our while
loop.

end
end



Back to top
Objects and methods
Some techniques and methodologies used in this code snippet may be new to you. Ruby is an object oriented programming (OOP) language. Using OOP, a programmer will typically call items such as objects and methods. An object is like a container. It holds variables and functions that are specific to itself. A method is something that is called, like a function to address an object. If we look at the previous example, we can show both an object and a method in action.
while enterWorld = STDIN.gets
enterWorld.chop!
Here we have an example of two objects and two methods. The first object is
enterWorld
the second object is
STDIN
. The
enterWorld
object is a user-defined object, and the
STDIN
object (short for Standard Input) is built into Ruby.
We also have two methods in this example. The first is
gets
and the second is
chop!
. As mentioned previously, methods address objects. Specifically, a method will perform an action within an object. With the
gets
method, we are telling Ruby to get the
STDIN
. When Ruby sees
gets
associated with
STDIN
, it will await keyboard input and a carriage return. In short,
STDIN.gets
is waiting for the user to type something and then hit Enter.
Our second method,
chop!
, is addressing our user-defined object
enterWorld
. The
chop!
method is telling
enterWorld
to chop (cut) the new lines and carriage returns off the data associated with the
enterWorld
object. If you do not use
chop!
(or
chomp!
) the following, within the context of the previous code, would never be true.
if enterWorld == $salut[0]
It would be false because without the use of
chop!
,
$salut[0]
would actually equal
$salut[0]/n
. The new line is caused by the input that the
STDIN
object received from the
gets
method. Using a carriage return will add the new line character to the end of the value.




Back to top
Conclusion
Ruby is a very powerful but easy-to-use language. If you are currently a programmer coming from the likes of C++, Perl, or Python, you will see some strong similarities (especially to Python). The next articles in the series will build on this introduction with more advanced topics such as using Ruby modules and file operations.




Back to top
Resources
For more Ruby basics, including an interview with Ruby creator, Yukihiro Matsumoto, read "Ruby: A new language" on developerWorks.

Take a look at the official Ruby Web site.

Visit the Ruby Garden.

Learn more about Ruby in The Ruby Cookbook.

Find out more about Ruby for Win32.

Stop in at the Ruby Central.

Check out the Ruby application archive, which is maintained by Ruby itself!

Take a look at a simple list of Ruby features, including a brief discussion of its advantages and disadvantages (available in English and German).

Take a look at the latest Ruby file updates from FileWatcher.org.

Read about Ruby for Windows users.

Visit Command Prompt, Joshua Drake's Web site.

Browse more Linux resources on developerWorks.

Browse more Open source resources on developerWorks.




Back to top
About the author

Joshua Drake is the co-founder of Command Prompt, Inc, a PostgreSQL and Linux custom development company. He is also the current author of the Linux Networking HOWTO, Linux PPP HOWTO, and Linux Consultants HOWTO. His most demanding project at this time is a new PostgreSQL book for O'Reilly, Practical PostgreSQL. He can be reached at jd@commandprompt.com.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: