Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Server Technologies - Ruby on Rails

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Ruby

The first several examples are simple command-line programs that demonstrate fundamental Ruby programming concepts.

Ruby

 

The first several examples are simple command-line programs that demonstrate fundamental Ruby programming concepts. The Ruby scripting language was developed by Yukihiro “Matz” Matsumoto in 1995 to be a flexible, object-oriented scripting language. Ruby’s syntax and conventions are intuitive—they attempt to mimic the way a developer thinks. Ruby is an interpreted language.

Installing Instant Rails

 

To run the Ruby scripts in this chapter, Ruby must first be installed on your system. In this chapter we use the Instant Rails package to run our applications. Instant Rails in-cludes Ruby, Rails, MySQL, Apache, PHP and other components necessary to create and run Rails applications. PHP is used specifically for phpMyAdmin, a web interface to MySQL. Instant Rails is a stand-alone Rails development and testing environment.

 

To install Instant Rails, download Instant Rails 1.7 from //rubyforge.org/frs/ ?group_id=904. Once the zip file is downloaded, extract its contents to a folder on your hard drive.

 

After installing Instant Rails, make sure that you stop any existing web servers on your computer such as IIS or Apache— Instant Rails needs port 80 to be available for using phpMyAdmin to administer MySQL. If you are not using this tool then you don’t need to stop other web servers on your computer. To run Instant Rails, navigate to the folder where you extracted the contents of the zip file and run InstantRails.exe. You should see a window similar to Fig. 24.1.

 

If you are using Mac OS X, there is an application similar to Instant Rails called Loco-motive. You can download Locomotive from locomotive.raaum.org. Linux users might want to try LinRails (available from linrails.thembid.com). Another program useful for Rails development is Aptana Radrails—a free, open-source IDE. Radrails can be downloaded from  www.aptana.com/download_rails_rdt.php.


Printing a Line of Text

Figure 24.2 presents a simple Ruby program that prints the text "Welcome to Ruby!". Lines 1–2 are single-line comments that instruct the interpreter to ignore everything on the current line following the # symbol. Line 3 uses the method puts that takes a single parameter (a string) and prints the text to the terminal, followed by a newline. A method can have parentheses surrounding its parameters, but this is not typical in Ruby unless they are used to avoid ambiguity. A line of Ruby code does not have to end with a semicolon, although one can be placed there. The puts method automatically adds a newline escape sequence (\n) at the end of the string if one is not explicitly added.

 

1    # Fig. 24.2: welcome.rb

 

2    # Simple Ruby program.

 

3    puts "Welcome to Ruby!"


 

 

Welcome to Ruby!

Fig. 24.2 | Simple Ruby program.

 

Running a Ruby Script

 

A Ruby script can be run several ways. One is to use the Ruby interpreter. To do so, launch Instant Rails, click the  button in the top-left corner and select Rails Applications > Open Ruby Console Window from the drop-down menu (see Fig. 24.3).

 

In the console, use the cd command to navigate to the directory where welcome.rb is located, then enter ruby welcome.rb. Figure 24.4 shows the Ruby interpreter executing the Ruby file from Fig. 24.2 in the Ruby Console window.

 

Ruby can also execute interactively, using IRB (Interactive Ruby). IRB interprets Ruby code statement by statement. This is useful for debugging code and for experi-menting with Ruby functionality. IRB can be run through Instant Rails by typing IRB in the Ruby Console. Figure 24.5 shows simple Ruby statements interpreted in IRB.

 

The code after the prompt (irb(main):001:0>) shows the statement that was exe-cuted using the Ruby interpreter in Fig. 24.4. It sends the same string to the output, then returns the value of method puts, which is nil, an object that represents nothing in Ruby.


The code after the second IRB prompt sends the arithmetic expression 2+2 to the interpreter, which evaluates the expression and returns 4. The code after the third prompt requests the class type of the number 4. The interpreter returns Fixnum—a class that rep-resents integers in Ruby. Last, the code after the fourth prompt calls the ceil method of 4.5 to round the number up to the next whole-number value. The IRB returns 5. Type

exit to quit IRB.

 

Variables and Data Types in Ruby

 

Like most scripting languages, Ruby uses dynamic typing, which allows changes to a vari-able’s type during runtime. There are several variable types in Ruby, including String and Fixnum. Everything is an object in Ruby, so you can call methods on any piece of data. Figure 24.6 invokes methods on numeric and string data.

 

Line 3 initializes the variable myvar. Setting myvar to 7.5 temporarily makes it a Float object. The highlighted portion of line 4 is an example of interpolation in Ruby. It inserts the object value of the variable inside the braces into the string. Lines 6 and 12 invoke the

 

10# Fig. 24.6: types.rb

 

11# Method calls on numeric and string data

 

12myvar = 5.7 # binds the value 5.7 to myvar

 

13puts "The value of myvar is #{myvar}"

5

15myvar = myvar.round # return a rounded value Fixnum

 

16puts "The rounded value of myvar is #{myvar}"

8

1    myvar = 5.4 # bind the value 5.4 to myvar

 

2      puts "The value of myvar is #{myvar}"

11

7      myvar = myvar.round # return a rounded value Fixnum

 

8      puts "The rounded value of myvar is #{myvar}"

14

11  myvar = "mystring" # bind the value 'mystring' to myvar

 

12  puts "The value of myvar is '#{myvar}'"

17

16  myvar = myvar.capitalize # capitalize the value of myvar

 

17  puts "The capitalized form of myvar is '#{myvar}'"

20

20  myvar = "my string" # bind the value 'my string' to myvar

 

21  puts "The value of myvar is '#{myvar}'"

23

25  myvar = myvar.capitalize # capitalize the value of myvar

 

26  puts "The capitalized form of myvar is '#{myvar}'"

 

 

The value of myvar is 5.7

The rounded value of myvar is 6

The value of myvar is 5.4

The rounded value of myvar is 5

The value of myvar is 'mystring'

The capitalized form of myvar is 'Mystring'

The value of myvar is 'my string'

The capitalized form of myvar is 'My string'

 

Fig. 24.6 | Method calls on numeric and string data.

 

round method on the Float object to demonstrate rounding a value up or down, respec-tively. The type of myvar changes to String in line 15. Lines 18 and 24 changes the first letter of the first word of this String by calling its capitalize method. A list of the avail-

able methods for the Ruby types can be found at  www.ruby-doc.org/core/.

 

Using Arrays and Hashes

 

Ruby provides both Arrays and Hashes to store data. Each stores a list of objects. In an Array, indices of type Fixnum are used to select an Object from the Array. In a Hash, Objects are mapped to other Objects in key/value pairs. Figure 24.7 shows an example of using both an Array and a Hash to store information.

 

Line 3 instantiates a Ruby Array. Array elements can be accessed by their index number in square brackets (line 5). You may also traverse Arrays backward by using neg-ative number indices. For example line 6 outputs the last array element. Line 8 reverses the elements in the Array with method reverse!. The exclamation point after the method name is a Ruby convention indicating that the object on which the method is called will be modified. Method reverse without an exclamation point returns a copy of the original array with its elements reversed. Many Ruby methods follow this convention.

 

Line 14 is an example of a Hash. The key/value pairs are separated by commas, and each key points to its corresponding value using the => operator. The value of a hash ele-ment can be found by passing in the key in square brackets, as shown in lines 16–17.

 

31# Fig. 24.7: arraysAndHashes.rb

 

32# Arrays and hashes in Ruby.

3 fruits = [ "mango", "orange""apple", "pear" ] # create an array

 

34puts "The length of the fruits array is #{fruits.length}" # output length

 

35puts "The first fruit is #{fruits[0]}" # output first element

 

36puts "The last fruit is #{fruits[-1]}\n\n" # output last element

7

37fruits.reverse! # reverse the order of the elements in the fruits array

 

38puts "The length of the fruits array is #{fruits.length}" # output length

 

39  puts "The first fruit is #{fruits[0]}" # output first element

 

40  puts "The last fruit is #{fruits[-1]}\n\n" # output last element

12

40  # a simple hash

 

41    food = { "mango" => "fruit", "banana" => "fruit", "onion" => "vegetable" }

 

42  puts "The length of the food hash is #{food.length}" # output length

 

43  puts "A mango is a #{food["mango"]}" # output value of key mango

 

44  puts "An onion is a #{food["onion"]}" # output value of key onion

 

The length of the fruits array is 4 The first fruit is mango

the last fruit is pear

 

The length of the fruits array is 4 The first fruit is pear

the last fruit is mango

 

The length of the food hash is 3

A mango is a fruit

An onion is a vegetable

Fig. 24.7 |  Arrays and hashes in Ruby.

 

Conditionals, Loops and Code Blocks

 

Like any other programming language, Ruby provides selection and repetition statements. In addition, Ruby has support for code blocks—groupings of Ruby statements that can be passed to a method as an argument. Figure 24.8 shows a program that returns a stu-dent’s letter grade based on a numerical grade.

 

Lines 3–15 of Fig. 24.8 contain a Ruby method definition. Methods must be defined in a program before they are used. All methods start with def and end with end. Methods do not have to specify parameter types, but they must specify the name of each parameter. Lines 4–14 show a nested ifelsifelse statement that returns an appropriate letter grade based on the numeric value the method receives as an argument. If a method does not include an explicit return statement Ruby returns the last value or variable it encoun-ters when executing the function.

 

Line 17 defines a Hash of students and their numeric grades. Lines 19–21 show an example of a code block. A method may have a parameter containing a block of code, such as the each method. The block of code appears in brackets directly after the method call. A code block is similar to a method, in that parameters can be passed into it. The param-eters for a code block are given between pipe characters (|) and are separated by commas. The parameters are followed immediately by the code block’s statements. The code block in lines 19–21 outputs a line of text based on the key/value pair of every key in the Hash.

 

1# Fig. 24.8: controlStatements.rb

 

43# Conditionals, loops, and codeblocks.

 

44def letter_grade( x ) # define method letterGrade

 

45       if x >= 90 # if x is greater than or equal to 90

 

46             "A" # grade is A

 

47       elsif x >= 80 # if x is greater than or equal to 80

 

48             "B" # grade is B

 

49       elsif x >= 70 # if x is greater than or equal to 70

 

50             "C" # grade is C

 

51         elsif x >= 60 # if x is greater than or equal to 60

 

52               "D" # grade is D

 

53         else # grade is less than 60

 

54               "F" # grade is F

 

55         end # if

 

56  end # method letterGrade

16

17 students = { "John" => 100, "Sue" => 92, "Tom" => 56, "Jill" => 80 }

 

18

46  students.each() { |key, value| # display the letter grade for each student

 

47         puts "#{key} received a #{letter_grade(value)}"

 

} # end codeblock

 

 

Jill received a B

Sue received a A

John received a A

Tom received a F

 

 

Fig. 24.8 | Conditionals, loops and codeblocks.

Classes

 

You can create your own classes and instantiate objects. Classes enable you to encapsulate methods and data. Figure 24.9 shows a class named Point that stores x-y coordinates.

 

Line 3 begins the class definition with the keyword class followed by the class name. The initialize method (lines 7–11), like constructors in other object-oriented lan-guages, is used to declare and initialize an object’s data. When each instance of a class maintains its own copy of a variable, the variable is known as an instance variable. Lines 8–9 use the @ symbol to define the instance variables x and y. Classes can also have class variables that are shared by all copies of a class. Class variables always begin with @@ (line 4) and are visible to all instances of the class in which they are defined. Line 10 increments @@num_points every time a new Point is defined.

 

You can create new classes by inheriting from existing ones and providing your own additional or enhanced functionality. Lines 14–16 override the inherited to_s method, which is a method of all Ruby objects. When an object is concatenated with a string, the method is implicitly called to convert the object to its string representation. Class Point’s to_s method for the Point class returns a string containing the x-y coordinates.

 

50# Fig. 24.9: Classes.rb

 

51# A Ruby class.

 

52class Point

 

53       @@num_points = 0 # initialize numPoints

54          

55       # create a new Point object

 

56       def initialize(x, y)

 

57             @x = x # initialize x-coordinate

 

58             @y = y # initialize y-coordinate

 

59               @@num_points +=1  # increment numPoints counter

 

60         end # method initialize

12

60         # return a string containing the x-y values

61         def to_s

 

62               return "x: #{@x}; y: #{@y}"

 

63         end # method to_s

17

74         # return how many Points have been instantiated

 

75         def num_points

 

76               return @@num_points

 

77         end # method numPoints

 

78  end # class Point

23

24  p = Point.new( 8, 9 ) # instantiate a Point

 

25  q = Point.new( 1, 1 ) # instantiate another Point

 

26  puts "the value of p is '#{p}'"

 

27  puts "the value of q is '#{q}'"

 

28  puts "the number of points created is #{p.num_points}"

 

the value of p is 'x: 8; y: 9' 

the value of q is 'x: 1; y: 1' 

the number of points created is 2

Fig. 24.9 | A Ruby class.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.