Ruby – Hashes

Ruby – Hashes ”; Previous Next A Hash is a collection of key-value pairs like this: “employee” = > “salary”. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. The order in which you traverse a hash by either key or value may seem arbitrary and will generally not be in the insertion order. If you attempt to access a hash with a key that does not exist, the method will return nil. Creating Hashes As with arrays, there is a variety of ways to create hashes. You can create an empty hash with the new class method − months = Hash.new You can also use new to create a hash with a default value, which is otherwise just nil − months = Hash.new( “month” ) or months = Hash.new “month” When you access any key in a hash that has a default value, if the key or value doesn”t exist, accessing the hash will return the default value − Live Demo #!/usr/bin/ruby months = Hash.new( “month” ) puts “#{months[0]}” puts “#{months[72]}” This will produce the following result − month month Live Demo #!/usr/bin/ruby H = Hash[“a” => 100, “b” => 200] puts “#{H[”a”]}” puts “#{H[”b”]}” This will produce the following result − 100 200 You can use any Ruby object as a key or value, even an array, so the following example is a valid one − [1,”jan”] => “January” Hash Built-in Methods We need to have an instance of Hash object to call a Hash method. As we have seen, following is the way to create an instance of Hash object − Hash[[key =>|, value]* ] or Hash.new [or] Hash.new(obj) [or] Hash.new { |hash, key| block } This will return a new hash populated with the given objects. Now using the created object, we can call any available instance methods. For example − Live Demo #!/usr/bin/ruby $, = “, ” months = Hash.new( “month” ) months = {“1” => “January”, “2” => “February”} keys = months.keys puts “#{keys}” This will produce the following result − [“1”, “2”] Following are the public hash methods (assuming hash is an array object) − Sr.No. Methods & Description 1 hash == other_hash Tests whether two hashes are equal, based on whether they have the same number of key-value pairs, and whether the key-value pairs match the corresponding pair in each hash. 2 hash.[key] Using a key, references a value from hash. If the key is not found, returns a default value. 3 hash.[key] = value Associates the value given by value with the key given by key. 4 hash.clear Removes all key-value pairs from hash. 5 hash.default(key = nil) Returns the default value for hash, nil if not set by default=. ([] returns a default value if the key does not exist in hash.) 6 hash.default = obj Sets a default value for hash. 7 hash.default_proc Returns a block if hash was created by a block. 8 hash.delete(key) [or] array.delete(key) { |key| block } Deletes a key-value pair from hash by key. If block is used, returns the result of a block if pair is not found. Compare delete_if. 9 hash.delete_if { |key,value| block } Deletes a key-value pair from hash for every pair the block evaluates to true. 10 hash.each { |key,value| block } Iterates over hash, calling the block once for each key, passing the key-value as a two-element array. 11 hash.each_key { |key| block } Iterates over hash, calling the block once for each key, passing key as a parameter. 12 hash.each_key { |key_value_array| block } Iterates over hash, calling the block once for each key, passing the key and value as parameters. 13 hash.each_key { |value| block } Iterates over hash, calling the block once for each key, passing value as a parameter. 14 hash.empty? Tests whether hash is empty (contains no key-value pairs), returning true or false. 15 hash.fetch(key [, default] ) [or] hash.fetch(key) { | key | block } Returns a value from hash for the given key. If the key can”t be found, and there are no other arguments, it raises an IndexError exception; if default is given, it is returned; if the optional block is specified, its result is returned. 16 hash.has_key?(key) [or] hash.include?(key) [or] hash.key?(key) [or] hash.member?(key) Tests whether a given key is present in hash, returning true or false. 17 hash.has_value?(value) Tests whether hash contains the given value. 18 hash.index(value) Returns the key for the given value in hash, nil if no matching value is found. 19 hash.indexes(keys) Returns a new array consisting of values for the given key(s). Will insert the default value for keys that are not found. This method is deprecated. Use select. 20 hash.indices(keys) Returns a new array consisting of values for the given key(s). Will insert the default value for keys that are not found. This method is deprecated. Use select. 21 hash.inspect Returns a pretty print string version of hash. 22 hash.invert Creates a new hash, inverting keys and values from hash; that is, in the new hash, the keys from hash become values and values become keys. 23 hash.keys Creates a new array with keys from hash. 24 hash.length Returns the size or length of hash as an integer. 25 hash.merge(other_hash) [or] hash.merge(other_hash) { |key, oldval, newval| block } Returns a new hash containing the contents of hash and other_hash, overwriting pairs in hash with duplicate keys with those from other_hash. 26 hash.merge!(other_hash) [or] hash.merge!(other_hash) { |key, oldval, newval| block } Same as merge, but changes are done in place. 27 hash.rehash Rebuilds hash based on the current values for each key. If values have changed since they were inserted, this method reindexes hash. 28 hash.reject { |key, value| block } Creates a new hash for every pair the block evaluates to true 29 hash.reject! { |key, value| block } Same as reject, but changes are made in place. 30 hash.replace(other_hash) Replaces the contents of hash with the

Ruby – Web Applications

Ruby Web Applications – CGI Programming ”; Previous Next Ruby is a general-purpose language; it can”t properly be called a web language at all. Even so, web applications and web tools in general are among the most common uses of Ruby. Not only can you write your own SMTP server, FTP daemon, or Web server in Ruby, but you can also use Ruby for more usual tasks such as CGI programming or as a replacement for PHP. Please spend few minutes with CGI Programming Tutorial for more detail on CGI Programming. Writing CGI Scripts The most basic Ruby CGI script looks like this − Live Demo #!/usr/bin/ruby puts “HTTP/1.0 200 OK” puts “Content-type: text/htmlnn” puts “<html><body>This is a test</body></html>” If you call this script test.cgi and uploaded it to a Unix-based Web hosting provider with the right permissions, you could use it as a CGI script. For example, if you have the Web site https://www.example.com/ hosted with a Linux Web hosting provider and you upload test.cgi to the main directory and give it execute permissions, then visiting https://www.example.com/test.cgi should return an HTML page saying This is a test. Here when test.cgi is requested from a Web browser, the Web server looks for test.cgi on the Web site, and then executes it using the Ruby interpreter. The Ruby script returns a basic HTTP header and then returns a basic HTML document. Using cgi.rb Ruby comes with a special library called cgi that enables more sophisticated interactions than those with the preceding CGI script. Let”s create a basic CGI script that uses cgi − Live Demo #!/usr/bin/ruby require ”cgi” cgi = CGI.new puts cgi.header puts “<html><body>This is a test</body></html>” Here, you created a CGI object and used it to print the header line for you. Form Processing Using class CGI gives you access to HTML query parameters in two ways. Suppose we are given a URL of /cgi-bin/test.cgi?FirstName = Zara&LastName = Ali. You can access the parameters FirstName and LastName using CGI#[] directly as follows − #!/usr/bin/ruby require ”cgi” cgi = CGI.new cgi[”FirstName”] # => [“Zara”] cgi[”LastName”] # => [“Ali”] There is another way to access these form variables. This code will give you a hash of all the key and values − #!/usr/bin/ruby require ”cgi” cgi = CGI.new h = cgi.params # => {“FirstName”=>[“Zara”],”LastName”=>[“Ali”]} h[”FirstName”] # => [“Zara”] h[”LastName”] # => [“Ali”] Following is the code to retrieve all the keys − #!/usr/bin/ruby require ”cgi” cgi = CGI.new cgi.keys # => [“FirstName”, “LastName”] If a form contains multiple fields with the same name, the corresponding values will be returned to the script as an array. The [] accessor returns just the first of these.index the result of the params method to get them all. In this example, assume the form has three fields called “name” and we entered three names “Zara”, “Huma” and “Nuha” − #!/usr/bin/ruby require ”cgi” cgi = CGI.new cgi[”name”] # => “Zara” cgi.params[”name”] # => [“Zara”, “Huma”, “Nuha”] cgi.keys # => [“name”] cgi.params # => {“name”=>[“Zara”, “Huma”, “Nuha”]} Note − Ruby will take care of GET and POST methods automatically. There is no separate treatment for these two different methods. An associated, but basic, form that could send the correct data would have the HTML code like so − <html> <body> <form method = “POST” action = “http://www.example.com/test.cgi”> First Name :<input type = “text” name = “FirstName” value = “” /> <br /> Last Name :<input type = “text” name = “LastName” value = “” /> <input type = “submit” value = “Submit Data” /> </form> </body> </html> Creating Forms and HTML CGI contains a huge number of methods used to create HTML. You will find one method per tag. In order to enable these methods, you must create a CGI object by calling CGI.new. To make tag nesting easier, these methods take their content as code blocks. The code blocks should return a String, which will be used as the content for the tag. For example − #!/usr/bin/ruby require “cgi” cgi = CGI.new(“html4”) cgi.out { cgi.html { cgi.head { “n”&plus;cgi.title{“This Is a Test”} } &plus; cgi.body { “n”&plus; cgi.form {“n”&plus; cgi.hr &plus; cgi.h1 { “A Form: ” } &plus; “n”&plus; cgi.textarea(“get_text”) &plus;”n”+ cgi.br + cgi.submit } } } } NOTE − The form method of the CGI class can accept a method parameter, which will set the HTTP method ( GET, POST, and so on…) to be used on form submittal. The default, used in this example, is POST. This will produce the following result − Content-Type: text/html Content-Length: 302 <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Final//EN”> <HTML> <HEAD> <TITLE>This Is a Test</TITLE> </HEAD> <BODY> <FORM METHOD = “post” ENCTYPE = “application/x-www-form-urlencoded”> <HR> <H1>A Form: </H1> <TEXTAREA COLS = “70” NAME = “get_text” ROWS = “10”></TEXTAREA> <BR> <INPUT TYPE = “submit”> </FORM> </BODY> </HTML> Quoting Strings When dealing with URLs and HTML code, you must be careful to quote certain characters. For instance, a slash character ( / ) has special meaning in a URL, so it must be escaped if it”s not part of the pathname. For example, any / in the query portion of the URL will be translated to the string %2F and must be translated back to a / for you to use it. Space and ampersand are also special characters. To handle this, CGI provides the routines CGI.escape and CGI.unescape. #!/usr/bin/ruby require ”cgi” puts CGI.escape(Zara Ali/A Sweet & Sour Girl”) This will produce the following result − Zara+Ali%2FA Sweet+%26+Sour+Girl”) #!/usr/bin/ruby require ”cgi” puts CGI.escapeHTML(”<h1>Zara Ali/A Sweet & Sour Girl</h1>”) This will produce the following result − &lt;h1&gt;Zara Ali/A Sweet & Sour Girl&lt;/h1&gt;” Useful Methods in CGI Class Here is the list of methods related to CGI class − The Ruby CGI − Methods related to Standard CGI library. Cookies and Sessions We have explained these two concepts in different sections. Please follow the sections − The Ruby CGI Cookies − How to handle CGI Cookies. The Ruby CGI Sessions − How to manage CGI sessions. Web Hosting Servers

Ruby – Strings

Ruby – Strings ”; Previous Next A String object in Ruby holds and manipulates an arbitrary sequence of one or more bytes, typically representing characters that represent human language. The simplest string literals are enclosed in single quotes (the apostrophe character). The text within the quote marks is the value of the string − ”This is a simple Ruby string literal” If you need to place an apostrophe within a single-quoted string literal, precede it with a backslash, so that the Ruby interpreter does not think that it terminates the string − ”Won”t you read O”Reilly”s book?” The backslash also works to escape another backslash, so that the second backslash is not itself interpreted as an escape character. Following are the string-related features of Ruby. Expression Substitution Expression substitution is a means of embedding the value of any Ruby expression into a string using #{ and } − Live Demo #!/usr/bin/ruby x, y, z = 12, 36, 72 puts “The value of x is #{ x }.” puts “The sum of x and y is #{ x + y }.” puts “The average was #{ (x + y + z)/3 }.” This will produce the following result − The value of x is 12. The sum of x and y is 48. The average was 40. General Delimited Strings With general delimited strings, you can create strings inside a pair of matching though arbitrary delimiter characters, e.g., !, (, {, <, etc., preceded by a percent character (%). Q, q, and x have special meanings. General delimited strings can be − %{Ruby is fun.} equivalent to “Ruby is fun.” %Q{ Ruby is fun. } equivalent to ” Ruby is fun. ” %q[Ruby is fun.] equivalent to a single-quoted string %x!ls! equivalent to back tick command output `ls` Escape Characters Following table is a list of escape or non-printable characters that can be represented with the backslash notation. NOTE − In a double-quoted string, an escape character is interpreted; in a single-quoted string, an escape character is preserved. Backslash notation Hexadecimal character Description a 0x07 Bell or alert b 0x08 Backspace cx   Control-x C-x   Control-x e 0x1b Escape f 0x0c Formfeed M-C-x   Meta-Control-x n 0x0a Newline nnn   Octal notation, where n is in the range 0.7 r 0x0d Carriage return s 0x20 Space t 0x09 Tab v 0x0b Vertical tab x   Character x xnn   Hexadecimal notation, where n is in the range 0.9, a.f, or A.F Character Encoding The default character set for Ruby is ASCII, whose characters may be represented by single bytes. If you use UTF-8, or another modern character set, characters may be represented in one to four bytes. You can change your character set using $KCODE at the beginning of your program, like this − $KCODE = ”u” Following are the possible values for $KCODE. Sr.No. Code & Description 1 a ASCII (same as none). This is the default. 2 e EUC. 3 n None (same as ASCII). 4 u UTF-8. String Built-in Methods We need to have an instance of String object to call a String method. Following is the way to create an instance of String object − new [String.new(str = “”)] This will return a new string object containing a copy of str. Now, using str object, we can all use any available instance methods. For example − Live Demo #!/usr/bin/ruby myStr = String.new(“THIS IS TEST”) foo = myStr.downcase puts “#{foo}” This will produce the following result − this is test Following are the public String methods ( Assuming str is a String object ) − Sr.No. Methods & Description 1 str % arg Formats a string using a format specification. arg must be an array if it contains more than one substitution. For information on the format specification, see sprintf under “Kernel Module.” 2 str * integer Returns a new string containing integer times str. In other words, str is repeated integer imes. 3 str &plus; other_str Concatenates other_str to str. 4 str << obj Concatenates an object to str. If the object is a Fixnum in the range 0.255, it is converted to a character. Compare it with concat. 5 str <=> other_str Compares str with other_str, returning -1 (less than), 0 (equal), or 1 (greater than). The comparison is case-sensitive. 6 str == obj Tests str and obj for equality. If obj is not a String, returns false; returns true if str <=> obj returns 0. 7 str =~ obj Matches str against a regular expression pattern obj. Returns the position where the match starts; otherwise, false. 8 str.capitalize Capitalizes a string. 9 str.capitalize! Same as capitalize, but changes are made in place. 10 str.casecmp Makes a case-insensitive comparison of strings. 11 str.center Centers a string. 12 str.chomp Removes the record separator ($/), usually n, from the end of a string. If no record separator exists, does nothing. 13 str.chomp! Same as chomp, but changes are made in place. 14 str.chop Removes the last character in str. 15 str.chop! Same as chop, but changes are made in place. 16 str.concat(other_str) Concatenates other_str to str. 17 str.count(str, …) Counts one or more sets of characters. If there is more than one set of characters, counts the intersection of those sets 18 str.crypt(other_str) Applies a one-way cryptographic hash to str. The argument is the salt string, which should be two characters long, each character in the range a.z, A.Z, 0.9, . or /. 19 str.delete(other_str, …) Returns a copy of str with all characters in the intersection of its arguments deleted. 20 str.delete!(other_str, …) Same as delete, but changes are made in place. 21 str.downcase Returns a copy of str with all uppercase letters replaced with lowercase. 22 str.downcase! Same as downcase, but changes are made in place. 23 str.dump Returns a version of str with all nonprinting characters replaced by nnn notation and all special characters escaped. 24 str.each(separator = &dollar;/) { |substr| block } Splits str using argument as the record

Ruby – Quick Guide

Ruby – Quick Guide ”; Previous Next Ruby – Overview 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. 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. Ruby – Environment Setup 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. Popular Ruby Editors To write your Ruby programs, you will need an editor − If you are working on Windows machine, then you can use any simple text editor like Notepad or Edit plus. VIM (Vi IMproved) is a very simple text editor. This is available on almost all Unix machines and now Windows as well. Otherwise, your can use your favorite vi editor to write Ruby programs. RubyWin is a Ruby Integrated Development Environment (IDE) for Windows. Ruby Development Environment (RDE) is also a very good IDE for windows users. Interactive Ruby (IRb) Interactive Ruby (IRb) provides a shell for experimentation. Within the IRb shell, you can immediately view expression results, line by line. This tool comes along with Ruby installation so you have nothing to do extra to have IRb working. Just type irb at your command prompt and an Interactive Ruby Session will start as given below − $irb irb 0.6.1(99/09/16) irb(main):001:0> def hello irb(main):002:1> out = “Hello World” irb(main):003:1> puts out irb(main):004:1> end nil irb(main):005:0> hello Hello World nil irb(main):006:0> Do not worry about what we did here. You will learn all these steps in subsequent chapters. What is Next? We assume now you have a working Ruby Environment and you are ready to write the first Ruby Program. The next chapter will teach you how to write Ruby programs. Ruby – Syntax Let us write a simple program in ruby. All ruby files will have extension .rb. So, put the following source code in a test.rb file. Live Demo #!/usr/bin/ruby -w puts “Hello, Ruby!”; Here, we assumed that you have Ruby interpreter available in /usr/bin directory. Now, try to run this program as follows − $ ruby test.rb This will produce the following result − Hello, Ruby! You have seen a simple Ruby program, now let us see a few basic concepts related to Ruby Syntax. Whitespace in Ruby Program Whitespace characters such as spaces and tabs are generally ignored in Ruby code, except when they appear in strings. Sometimes, however, they are used to interpret ambiguous statements. Interpretations of this sort produce warnings when the -w option is enabled. Example a + b is interpreted as a+b ( Here a is a local variable) a +b is interpreted as a(+b) ( Here a is a method call) Line Endings in Ruby Program Ruby interprets semicolons and newline characters as the ending of a statement. However, if Ruby encounters operators, such as &plus;, −, or backslash at the end of a line, they indicate the continuation of a statement. Ruby Identifiers Identifiers are names of variables, constants, and methods. Ruby identifiers are case sensitive. It means Ram and RAM are two different identifiers in Ruby. Ruby identifier names may consist of alphanumeric characters

Ruby – Classes and Objects

Ruby – Classes and Objects ”; Previous Next Ruby is a perfect Object Oriented Programming Language. The features of the object-oriented programming language include − Data Encapsulation Data Abstraction Polymorphism Inheritance These features have been discussed in the chapter Object Oriented Ruby. An object-oriented program involves classes and objects. A class is the blueprint from which individual objects are created. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. Take the example of any vehicle. It comprises wheels, horsepower, and fuel or gas tank capacity. These characteristics form the data members of the class Vehicle. You can differentiate one vehicle from the other with the help of these characteristics. A vehicle can also have certain functions, such as halting, driving, and speeding. Even these functions form the data members of the class Vehicle. You can, therefore, define a class as a combination of characteristics and functions. A class Vehicle can be defined as − Class Vehicle { Number no_of_wheels Number horsepower Characters type_of_tank Number Capacity Function speeding { } Function driving { } Function halting { } } By assigning different values to these data members, you can form several instances of the class Vehicle. For example, an airplane has three wheels, horsepower of 1,000, fuel as the type of tank, and a capacity of 100 liters. In the same way, a car has four wheels, horsepower of 200, gas as the type of tank, and a capacity of 25 liters. Defining a Class in Ruby To implement object-oriented programming by using Ruby, you need to first learn how to create objects and classes in Ruby. A class in Ruby always starts with the keyword class followed by the name of the class. The name should always be in initial capitals. The class Customer can be displayed as − class Customer end You terminate a class by using the keyword end. All the data members in the class are between the class definition and the end keyword. Variables in a Ruby Class Ruby provides four types of variables − Local Variables − Local variables are the variables that are defined in a method. Local variables are not available outside the method. You will see more details about method in subsequent chapter. Local variables begin with a lowercase letter or _. Instance Variables − Instance variables are available across methods for any particular instance or object. That means that instance variables change from object to object. Instance variables are preceded by the at sign (&commat;) followed by the variable name. Class Variables − Class variables are available across different objects. A class variable belongs to the class and is a characteristic of a class. They are preceded by the sign &commat;&commat; and are followed by the variable name. Global Variables − Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. The global variables are always preceded by the dollar sign (&dollar;). Example Using the class variable &commat;&commat;no_of_customers, you can determine the number of objects that are being created. This enables in deriving the number of customers. class Customer &commat;&commat;no_of_customers = 0 end Creating Objects in Ruby using new Method Objects are instances of the class. You will now learn how to create objects of a class in Ruby. You can create objects in Ruby by using the method new of the class. The method new is a unique type of method, which is predefined in the Ruby library. The new method belongs to the class methods. Here is the example to create two objects cust1 and cust2 of the class Customer − cust1 = Customer. new cust2 = Customer. new Here, cust1 and cust2 are the names of two objects. You write the object name followed by the equal to sign (=) after which the class name will follow. Then, the dot operator and the keyword new will follow. Custom Method to Create Ruby Objects You can pass parameters to method new and those parameters can be used to initialize class variables. When you plan to declare the new method with parameters, you need to declare the method initialize at the time of the class creation. The initialize method is a special type of method, which will be executed when the new method of the class is called with parameters. Here is the example to create initialize method − class Customer &commat;&commat;no_of_customers = 0 def initialize(id, name, addr) &commat;cust_id = id &commat;cust_name = name &commat;cust_addr = addr end end In this example, you declare the initialize method with id, name, and addr as local variables. Here, def and end are used to define a Ruby method initialize. You will learn more about methods in subsequent chapters. In the initialize method, you pass on the values of these local variables to the instance variables &commat;cust_id, &commat;cust_name, and &commat;cust_addr. Here local variables hold the values that are passed along with the new method. Now, you can create objects as follows − cust1 = Customer.new(“1”, “John”, “Wisdom Apartments, Ludhiya”) cust2 = Customer.new(“2”, “Poul”, “New Empire road, Khandala”) Member Functions in Ruby Class In Ruby, functions are called methods. Each method in a class starts with the keyword def followed by the method name. The method name always preferred in lowercase letters. You end a method in Ruby by using the keyword end. Here is the example to define a Ruby method − class Sample def function statement 1 statement 2 end end Here, statement 1 and statement 2 are part of the body of the method function inside the class Sample. These statments could be any valid Ruby statement. For example we can put a method puts to print Hello Ruby as follows − class Sample def hello puts “Hello Ruby!” end end Now in the following example, create one object of Sample class and call hello method and see the result

Ruby – Environment Setup

Ruby – Environment Setup ”; Previous Next 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. Popular Ruby Editors To write your Ruby programs, you will need an editor − If you are working on Windows machine, then you can use any simple text editor like Notepad or Edit plus. VIM (Vi IMproved) is a very simple text editor. This is available on almost all Unix machines and now Windows as well. Otherwise, your can use your favorite vi editor to write Ruby programs. RubyWin is a Ruby Integrated Development Environment (IDE) for Windows. Ruby Development Environment (RDE) is also a very good IDE for windows users. Interactive Ruby (IRb) Interactive Ruby (IRb) provides a shell for experimentation. Within the IRb shell, you can immediately view expression results, line by line. This tool comes along with Ruby installation so you have nothing to do extra to have IRb working. Just type irb at your command prompt and an Interactive Ruby Session will start as given below − $irb irb 0.6.1(99/09/16) irb(main):001:0> def hello irb(main):002:1> out = “Hello World” irb(main):003:1> puts out irb(main):004:1> end nil irb(main):005:0> hello Hello World nil irb(main):006:0> Do not worry about what we did here. You will learn all these steps in subsequent chapters. What is Next? We assume now you have a working Ruby Environment and you are ready to write the first Ruby Program. The next chapter will teach you how to write Ruby programs. Print Page Previous Next Advertisements ”;

Ruby – Variables

Ruby – Variables, Constants and Literals ”; Previous Next Variables are the memory locations, which hold any data to be used by any program. There are five types of variables supported by Ruby. You already have gone through a small description of these variables in the previous chapter as well. These five types of variables are explained in this chapter. Ruby Global Variables Global variables begin with &dollar;. Uninitialized global variables have the value nil and produce warnings with the -w option. Assignment to global variables alters the global status. It is not recommended to use global variables. They make programs cryptic. Here is an example showing the usage of global variable. Live Demo #!/usr/bin/ruby $global_variable = 10 class Class1 def print_global puts “Global variable in Class1 is #$global_variable” end end class Class2 def print_global puts “Global variable in Class2 is #$global_variable” end end class1obj = Class1.new class1obj.print_global class2obj = Class2.new class2obj.print_global Here $global_variable is a global variable. This will produce the following result − NOTE − In Ruby, you CAN access value of any variable or constant by putting a hash (#) character just before that variable or constant. Global variable in Class1 is 10 Global variable in Class2 is 10 Ruby Instance Variables Instance variables begin with &commat;. Uninitialized instance variables have the value nil and produce warnings with the -w option. Here is an example showing the usage of Instance Variables. Live Demo #!/usr/bin/ruby class Customer def initialize(id, name, addr) @cust_id = id @cust_name = name @cust_addr = addr end def display_details() puts “Customer id #@cust_id” puts “Customer name #@cust_name” puts “Customer address #@cust_addr” end end # Create Objects cust1 = Customer.new(“1”, “John”, “Wisdom Apartments, Ludhiya”) cust2 = Customer.new(“2”, “Poul”, “New Empire road, Khandala”) # Call Methods cust1.display_details() cust2.display_details() Here, &commat;cust_id, &commat;cust_name and &commat;cust_addr are instance variables. This will produce the following result − Customer id 1 Customer name John Customer address Wisdom Apartments, Ludhiya Customer id 2 Customer name Poul Customer address New Empire road, Khandala Ruby Class Variables Class variables begin with &commat;&commat; and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined. Overriding class variables produce warnings with the -w option. Here is an example showing the usage of class variable − Live Demo #!/usr/bin/ruby class Customer @@no_of_customers = 0 def initialize(id, name, addr) @cust_id = id @cust_name = name @cust_addr = addr end def display_details() puts “Customer id #@cust_id” puts “Customer name #@cust_name” puts “Customer address #@cust_addr” end def total_no_of_customers() @@no_of_customers += 1 puts “Total number of customers: #@@no_of_customers” end end # Create Objects cust1 = Customer.new(“1”, “John”, “Wisdom Apartments, Ludhiya”) cust2 = Customer.new(“2”, “Poul”, “New Empire road, Khandala”) # Call Methods cust1.total_no_of_customers() cust2.total_no_of_customers() Here &commat;&commat;no_of_customers is a class variable. This will produce the following result − Total number of customers: 1 Total number of customers: 2 Ruby Local Variables Local variables begin with a lowercase letter or _. The scope of a local variable ranges from class, module, def, or do to the corresponding end or from a block”s opening brace to its close brace {}. When an uninitialized local variable is referenced, it is interpreted as a call to a method that has no arguments. Assignment to uninitialized local variables also serves as variable declaration. The variables start to exist until the end of the current scope is reached. The lifetime of local variables is determined when Ruby parses the program. In the above example, local variables are id, name and addr. Ruby Constants Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally. Constants may not be defined within methods. Referencing an uninitialized constant produces an error. Making an assignment to a constant that is already initialized produces a warning. Live Demo #!/usr/bin/ruby class Example VAR1 = 100 VAR2 = 200 def show puts “Value of first Constant is #{VAR1}” puts “Value of second Constant is #{VAR2}” end end # Create Objects object = Example.new() object.show Here VAR1 and VAR2 are constants. This will produce the following result − Value of first Constant is 100 Value of second Constant is 200 Ruby Pseudo-Variables They are special variables that have the appearance of local variables but behave like constants. You cannot assign any value to these variables. self − The receiver object of the current method. true − Value representing true. false − Value representing false. nil − Value representing undefined. __FILE__ − The name of the current source file. __LINE__ − The current line number in the source file. Ruby Basic Literals The rules Ruby uses for literals are simple and intuitive. This section explains all basic Ruby Literals. Integer Numbers Ruby supports integer numbers. An integer number can range from -230 to 230-1 or -262 to 262-1. Integers within this range are objects of class Fixnum and integers outside this range are stored in objects of class Bignum. You write integers using an optional leading sign, an optional base indicator (0 for octal, 0x for hex, or 0b for binary), followed by a string of digits in the appropriate base. Underscore characters are ignored in the digit string. You can also get the integer value, corresponding to an ASCII character or escape the sequence by preceding it with a question mark. Example 123 # Fixnum decimal 1_234 # Fixnum decimal with underline -500 # Negative Fixnum 0377 # octal 0xff # hexadecimal 0b1011 # binary ?a # character code for ”a” ?n # code for a newline (0x0a) 12345678901234567890 # Bignum NOTE − Class and Objects are explained in a separate chapter of this tutorial. Floating Numbers Ruby supports floating numbers. They are also numbers but with decimals. Floating-point numbers are objects of class Float and can be any of the following −

Ruby – Syntax

Ruby – Syntax ”; Previous Next Let us write a simple program in ruby. All ruby files will have extension .rb. So, put the following source code in a test.rb file. Live Demo #!/usr/bin/ruby -w puts “Hello, Ruby!”; Here, we assumed that you have Ruby interpreter available in /usr/bin directory. Now, try to run this program as follows − $ ruby test.rb This will produce the following result − Hello, Ruby! You have seen a simple Ruby program, now let us see a few basic concepts related to Ruby Syntax. Whitespace in Ruby Program Whitespace characters such as spaces and tabs are generally ignored in Ruby code, except when they appear in strings. Sometimes, however, they are used to interpret ambiguous statements. Interpretations of this sort produce warnings when the -w option is enabled. Example a + b is interpreted as a+b ( Here a is a local variable) a +b is interpreted as a(+b) ( Here a is a method call) Line Endings in Ruby Program Ruby interprets semicolons and newline characters as the ending of a statement. However, if Ruby encounters operators, such as &plus;, −, or backslash at the end of a line, they indicate the continuation of a statement. Ruby Identifiers Identifiers are names of variables, constants, and methods. Ruby identifiers are case sensitive. It means Ram and RAM are two different identifiers in Ruby. Ruby identifier names may consist of alphanumeric characters and the underscore character ( _ ). Reserved Words The following list shows the reserved words in Ruby. These reserved words may not be used as constant or variable names. They can, however, be used as method names. BEGIN do next then END else nil true alias elsif not undef and end or unless begin ensure redo until break false rescue when case for retry while class if return while def in self __FILE__ defined? module super __LINE__ Here Document in Ruby “Here Document” refers to build strings from multiple lines. Following a << you can specify a string or an identifier to terminate the string literal, and all lines following the current line up to the terminator are the value of the string. If the terminator is quoted, the type of quotes determines the type of the line-oriented string literal. Notice there must be no space between << and the terminator. Here are different examples − Live Demo #!/usr/bin/ruby -w print <<EOF This is the first way of creating here document ie. multiple line string. EOF print <<“EOF”; # same as above This is the second way of creating here document ie. multiple line string. EOF print <<`EOC` # execute commands echo hi there echo lo there EOC print <<“foo”, <<“bar” # you can stack them I said foo. foo I said bar. bar This will produce the following result − This is the first way of creating her document ie. multiple line string. This is the second way of creating her document ie. multiple line string. hi there lo there I said foo. I said bar. Ruby BEGIN Statement Syntax BEGIN { code } Declares code to be called before the program is run. Example Live Demo #!/usr/bin/ruby puts “This is main Ruby Program” BEGIN { puts “Initializing Ruby Program” } This will produce the following result − Initializing Ruby Program This is main Ruby Program Ruby END Statement Syntax END { code } Declares code to be called at the end of the program. Example Live Demo #!/usr/bin/ruby puts “This is main Ruby Program” END { puts “Terminating Ruby Program” } BEGIN { puts “Initializing Ruby Program” } This will produce the following result − Initializing Ruby Program This is main Ruby Program Terminating Ruby Program Ruby Comments A comment hides a line, part of a line, or several lines from the Ruby interpreter. You can use the hash character (#) at the beginning of a line − # I am a comment. Just ignore me. Or, a comment may be on the same line after a statement or expression − name = “Madisetti” # This is again comment You can comment multiple lines as follows − # This is a comment. # This is a comment, too. # This is a comment, too. # I said that already. Here is another form. This block comment conceals several lines from the interpreter with =begin/=end − =begin This is a comment. This is a comment, too. This is a comment, too. I said that already. =end Print Page Previous Next Advertisements ”;

Ruby – Overview

Ruby – Overview ”; Previous Next 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. 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. Print Page Previous Next Advertisements ”;