Share E-Book

Ruby Programming Language (Tutorials Point)(Z-Library)

Author

Rating No ratings yet

Log in to rate

Programming Language
Language English

No Description

Format PDF
Size 2.4 MB
6
Views
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
i About the Tutorial Ruby is a scripting language designed by Yukihiro Matsumoto, also known as Matz. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives a complete understanding on Ruby. Audience This tutorial has been prepared for beginners to help them understand the basic to advanced concepts related to Ruby Scripting languages. Prerequisites Before you start practicing with various types of examples given in this tutorial, we are making an assumption that you are already aware of computer programs and programming languages in general. Copyright & Disclaimer Copyright 2015 by Tutorials Point (I) Pvt. Ltd. All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher. We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at contact@tutorialspoint.com
Page 3
ii Table of Contents About the Tutorial ...................................................................................................................................... Audience .................................................................................................................................................... i Prerequisites .............................................................................................................................................. i Copyright & Disclaimer .............................................................................................................................. i Table of Contents ...................................................................................................................................... ii 1. OVERVIEW .............................................................................................................................. 1 Features of Ruby ....................................................................................................................................... 1 Tools You Will Need .................................................................................................................................. 2 What is Next? ........................................................................................................................................... 2 2. ENVIRONMENT SETUP ............................................................................................................ 3 Try it Option Online .................................................................................................................................. 3 Local Environment Setup .......................................................................................................................... 3 Ruby Installation on Linux/Unix ................................................................................................................ 4 Using yum to Install Ruby ......................................................................................................................... 4 Ruby Installation on Windows .................................................................................................................. 5 Ruby Command Line Options .................................................................................................................... 5 Ruby Environment Variables ..................................................................................................................... 8 Popular Ruby Editors .............................................................................................................................. 10 Interactive Ruby (IRb) ............................................................................................................................. 10 What is Next? ......................................................................................................................................... 11 3. SYNTAX ................................................................................................................................. 12 Whitespace in Ruby Program .................................................................................................................. 12 Line Endings in Ruby Program ................................................................................................................. 12 Ruby Identifiers ...................................................................................................................................... 13
Page 4
iii Reserved Words ...................................................................................................................................... 13 Here Document in Ruby .......................................................................................................................... 13 Ruby BEGIN Statement ........................................................................................................................... 15 Ruby END Statement .............................................................................................................................. 15 Ruby Comments ...................................................................................................................................... 16 4. CLASSES AND OBJECTS .......................................................................................................... 18 Defining a Class in Ruby .......................................................................................................................... 19 Variables in a Ruby Class ......................................................................................................................... 19 Creating Objects in Ruby Using new Method .......................................................................................... 20 Custom Method to Create Ruby Objects ................................................................................................. 20 Member Functions in Ruby Class ............................................................................................................ 21 Simple Case Study ................................................................................................................................... 22 5. VARIABLES, CONSTANTS AND LITERALS ................................................................................ 26 Ruby Global Variables ............................................................................................................................. 26 Ruby Instance Variables .......................................................................................................................... 27 Ruby Class Variables ............................................................................................................................... 28 Ruby Local Variables ............................................................................................................................... 29 Ruby Constants ....................................................................................................................................... 29 Ruby Pseudo-Variables ........................................................................................................................... 30 Ruby Basic Literals .................................................................................................................................. 30 Integer Numbers ..................................................................................................................................... 31 Floating Numbers.................................................................................................................................... 31 String Literals .......................................................................................................................................... 31 Backslash Notations ................................................................................................................................ 32 Ruby Arrays ............................................................................................................................................ 33 Ruby Hashes ........................................................................................................................................... 34
Page 5
iv Ruby Ranges ........................................................................................................................................... 34 6. OPERATORS ........................................................................................................................... 36 Ruby Arithmetic Operators ..................................................................................................................... 36 Ruby Comparison Operators ................................................................................................................... 37 Ruby Assignment Operators ................................................................................................................... 38 Ruby Parallel Assignment........................................................................................................................ 39 Ruby Bitwise Operators .......................................................................................................................... 39 Ruby Logical Operators ........................................................................................................................... 40 Ruby Ternary Operator ........................................................................................................................... 41 Ruby Range Operators ............................................................................................................................ 41 Ruby defined? Operators ........................................................................................................................ 42 Ruby Dot "." and Double Colon "::" Operators ........................................................................................ 43 Ruby Operators Precedence .................................................................................................................... 44 7. COMMENTS .......................................................................................................................... 47 Ruby Multiline Comments ...................................................................................................................... 47 8. IF…ELSE, CASE, UNLESS ......................................................................................................... 49 Ruby if...else Statement ......................................................................................................................... 49 Ruby if modifier ...................................................................................................................................... 50 Ruby unless Statement ........................................................................................................................... 50 Ruby unless modifier .............................................................................................................................. 51 Ruby case Statement .............................................................................................................................. 52 9. LOOPS ................................................................................................................................... 54 Ruby while Statement ............................................................................................................................ 54 Ruby while modifier ............................................................................................................................... 55 Ruby until Statement .............................................................................................................................. 56
Page 6
v Ruby until modifier ................................................................................................................................. 56 Ruby for Statement ................................................................................................................................ 57 Ruby break Statement ............................................................................................................................ 59 Ruby next Statement .............................................................................................................................. 59 Ruby redo Statement ............................................................................................................................. 60 Ruby retry Statement ............................................................................................................................. 61 10. METHODS ........................................................................................................................... 63 Return Values from Methods .................................................................................................................. 64 Ruby return Statement ........................................................................................................................... 65 Variable Number of Parameters ............................................................................................................. 66 Class Methods ......................................................................................................................................... 67 Ruby alias Statement .............................................................................................................................. 67 Ruby undef Statement ............................................................................................................................ 68 11. BLOCKS................................................................................................................................ 69 The yield Statement ............................................................................................................................... 69 Blocks and Methods ................................................................................................................................ 71 BEGIN and END Blocks ............................................................................................................................ 72 12. MODULES AND MIXINS ....................................................................................................... 73 Ruby require Statement ......................................................................................................................... 74 Ruby include Statement ......................................................................................................................... 75 Mixins in Ruby ........................................................................................................................................ 76 13. STRINGS .............................................................................................................................. 79 Expression Substitution .......................................................................................................................... 79 General Delimited Strings ....................................................................................................................... 80 Escape Characters ................................................................................................................................... 80
Page 7
vi Character Encoding ................................................................................................................................. 81 String Built-in Methods ........................................................................................................................... 81 String unpack Directives.......................................................................................................................... 92 14. ARRAYS ............................................................................................................................... 96 Creating Arrays ....................................................................................................................................... 96 Array Built-in Methods ........................................................................................................................... 98 Array pack Directives ............................................................................................................................ 107 15. HASHES ............................................................................................................................. 111 Creating Hashes .................................................................................................................................... 111 Hash Built-in Methods .......................................................................................................................... 112 16. DATE AND TIME ................................................................................................................ 118 Getting Current Date and Time ............................................................................................................. 118 Getting Components of a Date & Time.................................................................................................. 118 Time.utc, Time.gm and Time.local Functions ....................................................................................... 119 Timezones and Daylight Savings Time ................................................................................................... 121 Formatting Times and Dates ................................................................................................................. 121 Time Formatting Directives ................................................................................................................... 122 Time Arithmetic .................................................................................................................................... 123 17. RANGES ............................................................................................................................. 125 Ranges as Sequences ............................................................................................................................ 125 Ranges as Conditions ............................................................................................................................ 127 Ranges as Intervals ............................................................................................................................... 128 18. ITERATORS ........................................................................................................................ 129 Ruby each Iterator ................................................................................................................................ 129 Ruby collect Iterator ............................................................................................................................. 130
Page 8
vii 19. FILE I/O.............................................................................................................................. 132 The puts Statement .............................................................................................................................. 132 The gets Statement .............................................................................................................................. 132 The putc Statement .............................................................................................................................. 133 The print Statement ............................................................................................................................. 133 Opening and Closing Files ..................................................................................................................... 134 The File.new Method ............................................................................................................................ 134 The File.open Method .......................................................................................................................... 134 Reading and Writing Files ..................................................................................................................... 135 The sysread Method ............................................................................................................................. 135 The syswrite Method ............................................................................................................................ 136 The each_byte Method ......................................................................................................................... 136 The IO.readlines Method ...................................................................................................................... 137 The IO.foreach Method ........................................................................................................................ 137 Renaming and Deleting Files ................................................................................................................. 138 File Modes and Ownership ................................................................................................................... 138 File Inquiries ......................................................................................................................................... 140 Directories in Ruby ................................................................................................................................ 141 Navigating Through Directories ............................................................................................................. 141 Creating a Directory .............................................................................................................................. 142 Deleting a Directory .............................................................................................................................. 142 Creating Files & Temporary Directories ................................................................................................. 142 Built-in Functions .................................................................................................................................. 143 File Class and Methods ......................................................................................................................... 143 Directory Class and Methods ................................................................................................................ 149 20. EXCEPTIONS ...................................................................................................................... 152
Page 9
viii Using retry Statement .......................................................................................................................... 153 Using raise Statement .......................................................................................................................... 154 Using ensure Statement ....................................................................................................................... 156 Using else Statement ............................................................................................................................ 157 Catch and Throw ................................................................................................................................... 158 Class Exception ..................................................................................................................................... 160 21. RUBY OBJECT ORIENTED ................................................................................................... 162 Ruby Class Definition ............................................................................................................................ 162 Define Ruby Objects ............................................................................................................................. 162 The initialize Method ............................................................................................................................ 163 The instance Variables .......................................................................................................................... 163 The accessor & setter Methods ............................................................................................................. 163 The instance Methods ........................................................................................................................... 166 The class Methods and Variables .......................................................................................................... 167 The to_s Method................................................................................................................................... 168 Access Control ...................................................................................................................................... 169 Class Inheritance ................................................................................................................................... 170 Methods Overriding .............................................................................................................................. 172 Operator Overloading ........................................................................................................................... 173 Freezing Objects.................................................................................................................................... 174 Class Constants ..................................................................................................................................... 175 Create Object Using Allocate................................................................................................................. 177 Class Information .................................................................................................................................. 178 22. REGULAR EXPRESSIONS ..................................................................................................... 179 Regular-Expression Modifiers ............................................................................................................... 179 Regular-Expression Patterns ................................................................................................................. 180
Page 10
ix Regular-Expression Examples ................................................................................................................ 183 Anchors ................................................................................................................................................. 186 Special Syntax with Parentheses ........................................................................................................... 187 Search and Replace ............................................................................................................................... 187 23. DBI .................................................................................................................................... 189 Architecture of a DBI Application .......................................................................................................... 189 Prerequisites ......................................................................................................................................... 190 Obtaining and Installing Ruby/DBI ........................................................................................................ 190 Database Connection ............................................................................................................................ 191 INSERT Operation ................................................................................................................................. 192 Using do Statement .............................................................................................................................. 192 Using prepare and execute ................................................................................................................... 194 READ Operation .................................................................................................................................... 195 Fetching the Result ............................................................................................................................... 197 Update Operation ................................................................................................................................. 203 DELETE Operation ................................................................................................................................. 204 Performing Transactions ....................................................................................................................... 205 COMMIT Operation .............................................................................................................................. 206 ROLLBACK Operation ............................................................................................................................ 206 Disconnecting Database ........................................................................................................................ 206 Handling Errors ..................................................................................................................................... 207 Code Blocks with Methods .................................................................................................................... 208 Driver-specific Functions and Attributes ............................................................................................... 209 24. WEB APPLICATIONS .......................................................................................................... 212 Writing CGI Scripts ................................................................................................................................ 212 Using cgi.rb ........................................................................................................................................... 212
Page 11
x Form Processing .................................................................................................................................... 213 Creating Forms and HTML ..................................................................................................................... 215 Quoting Strings ..................................................................................................................................... 216 Useful Methods in CGI Class .................................................................................................................. 217 Ruby CGI ............................................................................................................................................... 217 Cookies and Sessions ............................................................................................................................ 223 Ruby CGI Cookies .................................................................................................................................. 224 Ruby CGI Sessions ................................................................................................................................. 226 Web Hosting Servers ............................................................................................................................. 228 25. SENDING EMAIL ................................................................................................................ 229 Sending an HTML e-mail using Ruby ..................................................................................................... 231 Sending Attachments as an e-mail ........................................................................................................ 231 26. SOCKET PROGRAMMING ................................................................................................... 234 What are Sockets? ................................................................................................................................ 234 A Simple Client ...................................................................................................................................... 235 A Simple Server ..................................................................................................................................... 236 Multi-Client TCP Servers ....................................................................................................................... 236 A Tiny Web Browser ............................................................................................................................. 237 Further Readings ................................................................................................................................... 238 27. XML, XSLT, XPATH ............................................................................................................. 239 What is XML? ........................................................................................................................................ 239 XML Parser Architectures and APIs ....................................................................................................... 239 Parsing and Creating XML using Ruby ................................................................................................... 239 DOM-like Parsing .................................................................................................................................. 241 SAX-like Parsing .................................................................................................................................... 242
Page 12
xi XPath and Ruby .................................................................................................................................... 244 XSLT and Ruby ...................................................................................................................................... 245 Further Reading .................................................................................................................................... 247 28. WEB SERVICES ................................................................................................................... 248 What is SOAP? ...................................................................................................................................... 248 Installing SOAP4R.................................................................................................................................. 248 Writing SOAP4R Servers ........................................................................................................................ 249 Writing SOAP4R Clients ......................................................................................................................... 252 29. TK GUIDE ........................................................................................................................... 255 Introduction .......................................................................................................................................... 255 Installation ............................................................................................................................................ 255 Simple Tk Application ........................................................................................................................... 255 Ruby/Tk Widget Classes ........................................................................................................................ 256 TkFrame ................................................................................................................................................ 257 TkButton ............................................................................................................................................... 260 TkLabel ................................................................................................................................................. 264 TkEntry ................................................................................................................................................. 267 TkCheckButton...................................................................................................................................... 273 TkRadioButton ...................................................................................................................................... 277 TkListbox ............................................................................................................................................... 282 TkComboBox ......................................................................................................................................... 290 TkMenu ................................................................................................................................................ 291 TkMenubutton ...................................................................................................................................... 298 Tk.messageBox ..................................................................................................................................... 303 TkScrollbar ............................................................................................................................................ 304 TkCanvas ............................................................................................................................................... 310
Page 13
xii TkScale .................................................................................................................................................. 320 TkText ................................................................................................................................................... 326 TkToplevel ............................................................................................................................................ 331 TkSpinbox ............................................................................................................................................. 333 TkProgressBar ....................................................................................................................................... 340 Dialog Box ............................................................................................................................................. 343 Tk::Tile::Notebook ................................................................................................................................ 345 Tk::Tile::Paned ...................................................................................................................................... 348 Tk::Tile::Separator ................................................................................................................................ 351 Ruby/Tk Font, Colors, and Images ......................................................................................................... 353 Standard Configuration Options ........................................................................................................... 357 Ruby/Tk Geometry Management ......................................................................................................... 362 grid ....................................................................................................................................................... 363 Pack ...................................................................................................................................................... 364 Place ..................................................................................................................................................... 366 Ruby/Tk Event Handling ....................................................................................................................... 367 The configure Method .......................................................................................................................... 369 The cget Method .................................................................................................................................. 370 30. LDAP ................................................................................................................................. 371 Ruby/LDAP Installation ......................................................................................................................... 371 Establish LDAP Connection.................................................................................................................... 371 Adding an LDAP Entry ........................................................................................................................... 373 Modifying an LDAP Entry ...................................................................................................................... 375 Deleting an LDAP Entry ......................................................................................................................... 376 Modifying the Distinguished Name ....................................................................................................... 377 Performing a Search .............................................................................................................................. 378
Page 14
xiii Handling Errors ..................................................................................................................................... 379 Further Reading .................................................................................................................................... 380 31. MULTITHREADING............................................................................................................. 381 Creating Ruby Threads .......................................................................................................................... 381 Thread Lifecycle .................................................................................................................................... 382 Threads and Exceptions ........................................................................................................................ 383 Thread Variables ................................................................................................................................... 383 Thread Priorities ................................................................................................................................... 384 Thread Exclusion ................................................................................................................................... 385 Handling Deadlock ................................................................................................................................ 387 Thread States ........................................................................................................................................ 388 Thread Class Methods ........................................................................................................................... 388 Thread Instance Methods ..................................................................................................................... 390 32. BUILT-IN FUNCTIONS ........................................................................................................ 394 Functions for Numbers.......................................................................................................................... 401 Functions for Float ................................................................................................................................ 404 Functions for Math ............................................................................................................................... 405 Conversion Field Specifier ..................................................................................................................... 406 Test Function Arguments ...................................................................................................................... 408 33. PREDEFINED VARIABLES .................................................................................................... 411 34. PREDEFINED CONSTANTS .................................................................................................. 415 35. ASSOCIATED TOOLS........................................................................................................... 417 Standard Ruby Tools ............................................................................................................................. 417 RubyGems............................................................................................................................................. 417 Ruby Debugger ..................................................................................................................................... 421
Page 15
xiv Interactive Ruby .................................................................................................................................... 425 Ruby Profiler ......................................................................................................................................... 428 Additional Ruby Tools ........................................................................................................................... 429 eRuby: Embeded Ruby .......................................................................................................................... 429 ri: Ruby Interactive Reference ............................................................................................................... 431
Page 16
Ruby 1 Ruby is a pure object-oriented programming language. It was created in 1993 by Yukihiro Matsumoto of Japan. You can find the name Yukihiro Matsumoto on the Ruby mailing list at www.ruby-lang.org. Matsumoto is also known as Matz in the Ruby community. Ruby is "A Programmer's Best Friend". Ruby has features that are similar to those of Smalltalk, Perl, and Python. Perl, Python, and Smalltalk are scripting languages. Smalltalk is a true object- oriented language. Ruby, like Smalltalk, is a perfect object-oriented language. Using Ruby syntax is much easier than using Smalltalk syntax. Features of Ruby Ruby is an open-source and is freely available on the Web, but it is subject to a license. Ruby is a general-purpose, interpreted programming language. Ruby is a true object-oriented programming language. Ruby is a server-side scripting language similar to Python and PERL. Ruby can be used to write Common Gateway Interface (CGI) scripts. Ruby can be embedded into Hypertext Markup Language (HTML). Ruby has a clean and easy syntax that allows a new developer to learn very quickly and easily. Ruby has similar syntax to that of many programming languages such as C++ and Perl. Ruby is very much scalable and big programs written in Ruby are easily maintainable. Ruby can be used for developing Internet and intranet applications. Ruby can be installed in Windows and POSIX environments. Ruby support many GUI tools such as Tcl/Tk, GTK, and OpenGL. Ruby can easily be connected to DB2, MySQL, Oracle, and Sybase. Ruby has a rich set of built-in functions, which can be used directly into Ruby scripts. 1. OVERVIEW
Page 17
Ruby 2 Tools You Will Need For performing the examples discussed in this tutorial, you will need a latest computer like Intel Core i3 or i5 with a minimum of 2GB of RAM (4GB of RAM recommended). You also will need the following software: Linux or Windows 95/98/2000/NT or Windows 7 operating system Apache 1.3.19-5 Web server Internet Explorer 5.0 or above Web browser Ruby 1.8.5 This tutorial will provide the necessary skills to create GUI, networking, and Web applications using Ruby. It also will talk about extending and embedding Ruby applications. What is Next? The next chapter guides you to where you can obtain Ruby and its documentation. Finally, it instructs you on how to install Ruby and prepare an environment to develop Ruby applications.
Page 18
Ruby 3 Try it Option Online We already have set up Ruby Programming environment online, so that you can execute almost all the tutorial examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online. Try the following example using the Try it option available on our website at the top right corner of the sample code box given below: #!/usr/bin/ruby -w puts "Hello, Ruby!"; For most of the examples given in this tutorial, you will find a Try it option on our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning. Local Environment Setup If you are still willing to set up your environment for Ruby programming language, then let's proceed. This tutorial will teach you all the important topics related to environment setup. We would recommend you to go through the following topics first and then proceed further: Ruby Installation on Linux/Unix : If you are planning to have your development environment on Linux/Unix Machine, then go through this chapter. Ruby Installation on Windows : If you are planning to have your development environment on Windows Machine, then go through this chapter. Ruby Command Line Options : This chapter list out all the command line options, which you can use along with Ruby interpreter. Ruby Environment Variables : This chapter has a list of all the important environment variables to be set to make Ruby Interpreter works. 2. ENVIRONMENT SETUP
Page 19
Ruby 4 Ruby Installation on Linux/Unix Here are the steps to be followed to install Ruby on a Unix machine: NOTE: Before proceeding, make sure you have root privilege. Download a zipped file having latest version of Ruby. Follow Download Link. After having downloaded the Ruby archive, unpack it and change into the newly created directory: $ tar -xvzf ruby-1.6.7.tgz $ cd ruby-1.6.7 Now, configure and compile the source code as follows: $ ./configure $ make Finally, install Ruby interpreter as follows: $ su -l root # become a root user $ make install $ exit # become the original user again After installation, make sure everything is working fine by issuing the following command on the command-line: $ruby -v ruby 1.6.7 (2002-06-04) [i386-netbsd] If everything is fine, this should output the version of the installed Ruby interpreter as shown above. You may have installed different version, so it will display a different version. Using yum to Install Ruby If your computer is connected to the Internet, then the easiest way to install Ruby or any other other RPM is using the yum utility. Give the following command at the command prompt and you will find Ruby gets installed on your computer. $ yum install ruby
Page 20
Ruby 5 Ruby Installation on Windows Here are the steps to install Ruby on a Windows machine. NOTE: You may have different versions available at the time of installation. Download a zipped file having latest version of Ruby. Follow Download Link. After having downloaded the Ruby archive, unpack it and change into the newly created directory: Double-click the Ruby1.6.7.exe file. The Ruby installation wizard starts. Click Next to move to the Important Information page of the wizard and keep moving till Ruby installer completes installing Ruby. You may need to set some environment variables if your installation has not setup them appropriately. If you use Windows 9x, add the following lines to your c:\autoexec.bat: set PATH="D:\(ruby install directory)\bin;%PATH%" Windows NT/2000 users need to modify their registries. o Click Control Panel | System Properties | Environment Variables. o Under System Variables, select Path and click EDIT. o Add your Ruby directory to the end of the Variable Value list and click OK. o Under System Variables, select PATHEXT and click EDIT. o Add .RB and .RBW to the Variable Value list and click OK. After installation, make sure everything is working fine by issuing the following command on the command-line: $ruby -v ruby 1.6.7 If everything is fine, this should output the version of the installed Ruby interpreter as shown above. You may have installed different version, so it will display a different version. Ruby Command Line Options Ruby is generally run from the command line in the following way: $ ruby [ options ] [.] [ programfile ] [ arguments ... ]
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List