Friday, June 30, 2006

Writing our own Class

A class is a combination of state (for example, the quantity and the product id) and methods that use the state.

The Object is the parent class of all classes in Ruby. Its methods are therefore available to all objects unless explicitly overridden.

Let's write our own class - MotorCycle.rb.
class MotorCycle
def initialize(make, color)
# Instance variables
@make = make
@color = color
end
def startEngine
if (@engineState)
puts 'Engine Running'
else
@engineState = true
puts 'Engine Idle'
end
end
def dispAttr
puts 'Color of MotorCycle is ' + @color
puts 'Make of MotorCycle is ' + @make
end
m = MotorCycle.new('Yamaha', 'red')
m.startEngine
m.dispAttr
m.startEngine
end

Read this very carefully, it's a brain bender! Classes in Ruby are first-class objects - each is an instance of class Class. When a new class is defined (typically using class Name ... end), an object of type Class is created and assigned to a constant (Name. in this case). When Name.new is called to create a new object, the new instance method in Class is run by default, which in turn invokes allocate to allocate memory for the object, before finally calling the new object's initialize method.

A class's instance methods are public by default; anyone can call them. Let's refer to the program ClassAccess.rb below. The private directive is the strictest; private methods can only be called from within the same instance. Protected methods can be called in the same instance and by other instances of the same class and its subclasses.
class ClassAccess
def m1 # this method is public
end
protected
def m2 # this method is protected
end
private
def m3 # this method is private
end
end
Instance variables are not directly accessible outside the class. To make them available, Ruby provides accessor methods that return their values. The program Accessor.rb illustrates the same.
# Accessor.rb
# First without accessor methods
class Song
def initialize(name, artist)
@name = name
@artist = artist
end
def name
@name
end
def artist
@artist
end
end

song = Song.new("Brazil", "Ricky Martin")
puts song.name
puts song.artist

# Now, with accessor methods
class Song
def initialize(name, artist)
@name = name
@artist = artist
end
# the instance variable @name and @artist will
# be automatically created below
attr_reader :name, :artist # create reader only
# For creating reader and writer methods
# attr_accessor :name
# For creating writer methods
# attr_writer :name

end

song = Song.new("Brazil", "Ricky Martin")
puts song.name
puts song.artist
There are many classes and modules (more on this later) built into the standard Ruby language. They are available to every Ruby program automatically; no require is required. Some built-in classes are Array, Bignum, Class, Dir, Exception, File, Fixnum, Float, Integer, IO, Module, Numeric, Object, Range, String, Thread, Time. Some built-in Modules are Comparable, Enumerable, GC, Kernel, Math. The following Class Hierarchy is informative.

Inheritance allows you to create a class that is a refinement or specialization of another class. Refer program Inherit.rb.
class GF
def initialize
puts 'In GF class'
end
def gfmethod
puts 'GF method call'
end
end

# class F sub-class of GF
class F < GF
def initialize
puts 'In F class'
end
end

# class S sub-class of F
class S < F
def initialize
puts 'In S class'
end
son = S.new
son.gfmethod
end

First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Thursday, June 29, 2006

Reading from / Writing to Text files

Let's look at how we can read / write to a text file with the help of a simple program ReadWrite.rb.
# Open and read from a text file
File.open('Constructs.rb', 'r') do |f1|
while line = f1.gets
puts line
end
end

# Create a new file and write to it
File.open('Test.rb', 'w') do |f2|
# use "" for two lines of text
f2.puts "Created by Satish\nThank God!"
end
The File.open method can open the file in different modes like 'r' Read-only, starts at beginning of file (default); 'r+' Read/Write, starts at beginning of file; 'w' Write-only, truncates existing file to zero length or creates a new file for writing. Please check the online documentation for a full list of modes available. File.open opens a new File if there is no associated block. If the optional block is given, it will be passed file as an argument, and the file will automatically be closed when the block terminates.

Assignment: Write a Ruby program (call it SwapContents.rb) to do the following. Take two text files say A and B. The program should swap the contents of A and B ie. after the program is executed, A should contain B's contents and B should contains A's. Post your program as a comment to this post.

First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Own methods in Ruby

Let's look at writing one's own methods in Ruby with the help of a simple program MyMethods.rb.
# A simple method
def hello
puts 'Hello'
end
#use the method
hello

# Method with an argument - 1
def hello1(name)
puts 'Hello ' + name
return 'success'
end
puts(hello1('satish'))

# Method with an argument - 2
def hello1 name2
puts 'Hello ' + name2
return 'success'
end
puts(hello1 'satish')


First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Wednesday, June 28, 2006

Arrays in Ruby

An array is just a list in your computer. Every slot in the list acts like a variable: you can see what object a particular slot points to, and you can make it point to a different object. Arrays are best explained by the following example Arrays.rb.
# Arrays

# Empty array
var1 = []
# Array index starts from 0
puts var1[0]

# an array holding a single number
var2 = [5]
puts var2[0]

# an array holding two strings
var3 = ['Hello', 'Goodbye']
puts var3[0]
puts var3[2]

flavour = 'mango'
# an array whose elements are pointing
# to three objects - a float, a string and an array
var4 = [80.5, flavour, [true, false]]
puts var4[2]

name = ['Satish', 'Talim', 'Ruby', 'Java']
puts name[0]
puts name[1]
puts name[2]
puts name[3]
# the next one outputs nil
# nil is Ruby's way of saying nothing
puts name[4]
# we can add more elements too
name[4] = 'Pune'
puts name[4]
# we can add anything!
name[5] = 4.33
puts name[5]
# we can add an array to an array
name[6] = [1, 2, 3]
puts name[6]

# some methods on arrays
newarr = [45, 23, 1, 90]
puts newarr.sort
puts newarr.length

# method each (iterator) - extracts each element into lang
languages = ['Pune', 'Mumbai', 'Bangalore']

languages.each do |lang|
puts 'I love ' + lang + '!'
puts 'Don\'t you?'
end
The method each allows us to do something (whatever we want) to each object the array points to. In the example, we are able to go through each object in the array without using any numbers.


First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Some Methods in Ruby

Let us explore some methods in Ruby. So far we had seen a method like puts that writes to the screen. How does one accept user input? For this gets and chomp are useful. The example (Methods.rb) below illustrates the same.
# gets and chomp
puts "In which city do you stay?"
STDOUT.flush
city = gets.chomp
puts "The city is " + city
chomp is a string method and gets retrieves only strings from your keyboard. You must have realised that gets returns a string and a '\n' character, while chomp removes this '\n'.

There are many methods in the String class (you don't have to memorize them all; you can look up the documentation) like the reverse that gives a backwards version of a string (reverse does not change the original string). length that tells us the number of characters (including spaces) in the string. upcase changes every lowercase letter to uppercase, and downcase changes every uppercase letter to lowercase. swapcase switches the case of every letter in the string, and finally, capitalize is just like downcase, except that it switches the first character to uppercase (if it is a letter).

More on methods: If objects (such as strings, integers and floats) are the nouns in Ruby language, then methods are the verbs. Every method needs an object. It's usually easy to tell which object is performing the method: it's what comes right before the dot. Sometimes, though, it's not quite as obvious. When we are using puts, gets - where are their objects? In Ruby, the implicit object is whatever object you happen to be in. But we don't even know how to be in an object yet; we've always been inside a special object Ruby has created for us that represents the whole program. You can see always see what object you are in by using the special variable self.


First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Simple Constructs in Ruby

Today, we shall explore some very simple constructs available in Ruby. The example below (Constructs.rb) illustrates the if else end construct.
# if else end
var = 5
if var > 4
puts "Variable is greater than 4"
puts "I can have multiple statements here"
if var == 5
puts "Nested if else possible"
else
puts "Too cool"
end
else
puts "Variable is not greater than 5"
puts "I can have multiple statements here"
end
An example of using elsif is there in the program ElsIfEx.rb

Some common conditional operators are: ==, != >=, <=, >, <

Loops like the while are available. Again, the example below illustrates the same.
# Loops
var = 0
while var < 10
puts var.to_s
var += 1
end

I shall talk about another construct the do end when we discuss arrays.

First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Tuesday, June 27, 2006

Strings in Ruby

Let us explore Strings in Ruby. We refer to a group of letters in a program as strings. Strings can have punctuation, digits, symbols, and spaces in them...more than just letters. '' does not have anything in it at all; we call that an empty string. Here's the program RubyStrings.rb
=begin
Ruby Strings
=end

puts "Hello World"
# Can use " or ' for Strings, but ' is more efficient
puts 'Hello World'
# String concatenation
puts 'I like' + ' Ruby'
# Escape sequence
puts 'It\'s my Ruby'
# New here, displays the string three times
puts 'Hello' * 3
# Defining a constant
PI = 3.1416
puts PI
# Defining a local variable
myString = 'I love my city, Pune'
puts myString
=begin
Conversions
.to_i, .to_f, .to_s
=end
var1 = 5;
var2 = '2'
puts var1 + var2.to_i
Questions asked by the participants:
1. Sharif Kazi - Please explain how memory is managed for Strings in Ruby? Is there a separate pool for Strings?
Answer: Strings are objects of class String. The String class has more than 75 standard methods. If you refer to Ruby User's Guide, it says that "we do not have to consider the space occupied by a string. We are free from all memory management."

2. Anish - It's to be noted that any given variable can at different times hold references to objects of many different types. - Does that mean a variable of type x can hold reference to the variable of type b without direct relation (inheritance) between them?
Answer: Please go thro' the code in the program DiffObjects.rb We can assign an object to a variable. Also, we can reassign a different object to that variable. In fact, variables can point to just about anything...except other variables. So in the program, when we tried var2 = var1, it really pointed to 8 instead. Then with var1 = 'eight', we had var1 point to the string 'eight', but since var2 was never really pointing at var1, it stays pointing at the number 8.

3. Deepali - Do we have something like print of Java?
Answer: Yes, we do have that in Ruby. Write a Ruby program that has this statement and check the output.
STDOUT.print("This is a string")


First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Numbers in Ruby

Let's play with Numbers. In Ruby, numbers without decimal points are called integers, and numbers with decimal points are usually called floating-point numbers or, more simply, floats. Here's the program RubyNumbers.rb
=begin
Ruby Numbers
Usual operators:
+ addition
- subtraction
* multiplication
/ division
=end

puts 1 + 2
puts 2 * 3
# Integer division
# When you do arithmetic with integers, you'll get integer answers
puts 3 / 2
puts 10 - 11
puts 1.5 / 2.6
Questions asked by the participants:
1. Jatinder Singh - How do I get the integer result for the following operation (the desired output is 2) - puts 5.5/2
Answer: Try this -
num = 5.5 /2
puts num
puts num.to_int


First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Names in Ruby

Now, let us look at Names in Ruby.
  1. Names - Ruby names are used to refer to constants, variables, methods, classes, and modules (more of this later). The first character of a name helps Ruby to distinguish its intended use. Certain names, are reserved words and should not be used as variable, method, class, or module names. Lowercase letter means the characters ''a'' though ''z'', as well as ''_'', the underscore. Uppercase letter means ''A'' though ''Z,'' and digit means ''0'' through ''9.'' A name is an uppercase letter, lowercase letter, or an underscore, followed by Name characters: any combination of upper- and lowercase letters, underscore and digits.
  2. Variables - Variables in Ruby can contain data of any type. You can use variables in your Ruby programs without any declarations. Variable name itself denotes its scope (local, global, instance, etc.).
    1. A local variable name consists of a lowercase letter followed by name characters (sunil, myCount, _z, hit_and_run).
    2. An instance variable name starts with an ''at'' sign (''@'') followed by an upper- or lowercase letter, optionally followed by name characters (@sign, @_, @Counter).
    3. A class variable name starts with two ''at'' signs (''@@'') followed by an upper- or lowercase letter. optionally followed by name characters (@@sign, @@_, @@Counter).
    4. A constant name starts with an uppercase letter followed by name characters. Class names and module names are constants, and follow the constant naming conventions. By convention, constant variables are normally spelled using uppercase letters and underscores throughout (module MyMath, PI=3.1416, class MyPune).
    5. Global variables start with a dollar sign (''$'') followed by name characters. A global variable name can be formed using ''$-'' followed by any single character ($counter, $COUNTER, $-x).
  3. Method names should begin with a lowercase letter. ''?'' and ''!'' are the only weird characters allowed as method name suffixes (More on this later).


The Ruby convention is to use underscores to separate words in a multiword method or variable name. For Class names, module names and constants the convention is to use capitalization, rather than underscores, to distinguish the start of words within the name.

It's to be noted that any given variable can at different times hold references to objects of many different types. A Ruby constant is also a reference to an object. Constants are created when they are first assigned to (normally in a class or module definition; they should not be defined in a method - more of this later). Ruby lets you alter the value of a constant, although this will generate a warning message. Also, variables in Ruby act as "references" to objects which undergo automatic garbage collection.

Questions asked by the participants:
1. Shantanu - If I declare a variable 'x', and later on I want to make it global, can I do that?

2. Jatinder Singh - What is the scope of a global variable? Can I access them between two different files? A lot of relevant questions are coming into my mind like, what if a global variable already declared somewhere else is declared again with the same name (shadowing variables?) Also, what is the difference between Constants and Global Variables?


First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Some features of Ruby

Now, let us explore some of the features of Ruby.
  1. Free format
  2. Case sensitive
  3. Comments - Anything following an unquoted #, to the end of the line on which it appears, is ignored by the interpreter. Also, to facilitate large comment blocks, the ruby interpreter also ignores anything between a line starting with "=begin" and another line starting with "=end"
  4. Statement delimiters - Multiple statements on one line must be separated by semicolons, but they are not required at the end of a line; a linefeed is treated like a semicolon. If a line ends with a backslash (\), the linefeed following it is ignored; this allows you to have a single logical line that spans several lines
  5. Documentation - The complete documentation for Ruby is available online here.


First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Sunday, June 25, 2006

Ruby Quotes

Here are some Ruby Quotes to egg us on:

Dave Thomas:


And now, for the first time, I can seriously say that Ruby is ready for the enterprise. The language is stable, the libraries are great, and there is a growing pool of talented and enthusiastic Ruby developers, all rising to the challenge. We see companies such as Amazon and EarthLink using Ruby for both internal- and external-facing projects.




Technorati Tags: ,
Blogs linking to this article

Saturday, June 24, 2006

First Ruby program

Let's start our Ruby editor SciTE. To do so, on your windows desktop click on start/Programs/Ruby/Ruby182-15/SciTE Editor. The editor window opens. Press the F8 key to open an output window. Now, click on Options/Open Global Options File and search for 'tabsize'. Edit and make tabsize=2 and indent.size=2. Press Ctrl+S and the Ctrl+W. We are now ready to write our first Ruby program.


OBJECTIVE

Ruby and Rails covered here will give you the grounding you need to understand Rails code and write your own Rails applications.


Create a folder named say rubyprograms on your C:\ We shall store all our programs in this folder. Our first program will display the string "Hello" on the command window and the name of the program will be Hello.rb

All Ruby source files have the .rb file extension. In the left window of SciTE type puts 'Hello' and then click File/Save As... Give the name Hello.rb and store it in your rubyprograms folder. Press F5 to run your program. You should see Hello in the output window on the right.

Note: puts (s in puts stands for string; puts really means put string) simply writes onto the screen whatever comes after it. In Ruby, everything from an integer to a string is considered to be an object. And each object has built in 'methods' which can be used to do various useful things. To use a method, you need to put a dot after the object, then append the method name. Some methods such as puts and gets are available everywhere and don't need to be associated with a specific object. Technically speaking, these methods are provided by Ruby's Kernel module and they are included in all Ruby objects. When you run a Ruby application, an object called main is automatically created and this object provides access to the Kernel methods (Reference: The Little Book of Ruby).

Observe:
(a) Java and C programmers - no main method/function
(b) I am using single quotes around Hello. We can use " or ' for Strings, but ' is more efficient - more on this later
(c) The Ruby standard is to use two spaces for indentation


First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Friday, June 23, 2006

List of Resources

Here's a list of resources that we may refer to:

A. Ruby Resources

1. Books/eBooks/Magazines

2. Useful Links

3. Blogs

4. Forums/User Groups

5. Companies in India working in Ruby/Rails


B. Rail Resources
1. Books/eBooks/Magazines
2. Useful Links


First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Know the participants

I would like you to meet all the participants in this Ruby/Rails training programme.

Gaurav Bagga from Pune and a software professional
Abhijit Paranjpe from Pune and a Java professional
Anil Wadghule from Pune, a cool blogger and about to make a career in the I.T. field
Anish Betawadkar from Pune and a Project Manager with experience in VB, Oracle PL/SQL
Ashish Kulkarni from Stirling, Scotland, a Senior Consultant at SAP For Business Ltd., UK
Ashwini Khanna
Vaidehi Keskar
Deepali Ahirrao from Pune and working at Persistent
Eswar Malla from Visakhapatnam and about to make a career in the I.T. field and shifting to Bangalore soon
Gajendra Pingalkar from Pune and about to enter the I.T. field
Gaurav Kotak from San Francisco, USA, in the process of incubating an eCommernce mashup - GiftLasso.com. Plans to use Ruby for the development
Hemanshu Narsana from Pune about to enter the I.T. field
Jatinder Singh from Pune and worked on Test Automation and Web projects
Jai Porje from Pune working with ECMi Software Pvt Ltd
Dhanashree Angolkar from Pune working with ECMi Software Pvt Ltd
Suhas Nehete
Jincy John from Mumbai currently pursuing MBA(IT) from Symbiosis, Pune
Kaustubh Bhat from Pune and a .NET professional
Manoj Sagar from Ambajogai district Beed and a Java professional working in Aurangabad
Nitin Asati from Pune working on ASP, AJAX
Rajesh Kumar from Bangalore and a software professional
Sachin Joshi from Pune and an experienced User Interface Designer
Sandeep Suryavanshi from Pune and a Java professional
Sandip Deshmane from Pune and a Java professional
Shambhu Sinha from Pune and an experienced Java professional
Shantanu Mahajan from Pune with knowledge of scripting languages
Sharif Kazi from Pune with a background in J2EE
Smita Deshpande from Pune and working with Persistent, with background in Perl
Tejaswini Patwardhan from Pune and a Java professional; scored 95% in SCJP4
Pooja Palan from Mumbai and working with TCS
Vasudev Ram from Pune, an independent software consultant
Yogesh
Vishal Solanke from Aurangabad and works in IXIA Technologies Pvt Ltd
Vikrant Chaudhari from Pune and working with Reevik as a Java developer
Shilpa Waghmare
Nick Audo from Sebago, USA and an I.T. professional
Scot Gardner from Pennsylvania, USA and has been developing web applications in PHP/MySQL for the last 4 years as a hobby
Dave Rose from Cleveland, Ohio, USA and a DBA of a utility billing system for a small division of a local Govt.; 30 years in the programming business
Robert Gremillion from Houston, Texas, USA and an Oracle programmer
Patrick Berkeley from San Fransisco, USA with background in C, HTML, CSS
Zahir Khan from Pune and about to make a career in the I.T. field

It's my sincere request that each one of you post a comment here, letting us know the following:
(a) Your full name
(b) Where you are from
(c) Your technical background


First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Thursday, June 22, 2006

Let's get started

Let's get started.

First, What is Ruby? Ruby is a cross-platform interpreted language which has many features in common with other 'scripting' languages such as Perl and Python. However, its version of object orientation is more thorough than those languages and, in many respects, it has more in common with Smalltalk. In Ruby, everything you manipulate is an object, and the results of those manipulations are themselves objects. The Ruby language was created in 1993 by Yukihiro Matsumoto (commonly known as 'Matz').


27th June @ 8.00 hrs

Remember you need to comment here and say that you have installed Ruby on your PC.


Next, What is Rails? Currently much of the excitement surrounding Ruby can be attributed to a web development framework called Rails - popularly known as 'Ruby On Rails'. Ruby and Rails covered here will give you the grounding you need to understand Rails code and write your own Rails applications.

Today, Download Ruby plus an Editor.The simplest way to get Ruby installed on a PC is by using the Ruby Installer for Windows. Click on ruby182-15.exe This includes the SciTE code editor. Ruby releases with even subversion numbers - 1.6, 1.8, and so on - are stable, public releases. Install Ruby on your PC. After you have installed your Ruby software, the System Environment Variable path is already set to point to the bin folder of Ruby.

Do note that these instruction assume that you are going to use a Windows platform. For other platforms, I would request our participant Shantanu to post his comments on the process.

Ruby is the interpreted language, so you don't have to recompile to execute the program written in Ruby.

Questions asked by the participants:
1. Vikrant Chaudhari - Please explain the statement "Ruby is a Dynamic programming language."
Answer: In computer science, a dynamic programming language is a kind of programming language in which programs can change their structure as they run: functions may be introduced or removed, new classes of objects may be created, new modules may appear. Refer here for more details.


In the next session, we shall start writing Ruby programs.


First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Learn Ruby/Rails with me

Ruby: A Programmer's Best Friend
I have been toying with the idea of teaching/learning Ruby/Rails on the net along with some students. Finally, some have agreed and I have decided to give it a go, starting Monday, 26th June 2006.

For those who are interested, you need to do the following:
(a) First, I shall send you all an invite to join the PuneRuby group. It's free.
(b) We shall start learning Ruby/Rails from Monday, 26th June 2006. I shall post everyday something about the same on this blog. You should check this blog atleast once a day and comment about your queries, questions, doubts. I shall answer them here only.
(c) To be able to comment on this blog, you need a blogger account (free).
(d) Go to http://www.blogger.com/start
(e) Click on CREATE YOU BLOG NOW
(f) On the next page, create your account. While doing so, please give your firstname+lastname as Display name. Complete the form.
(g) Kindly do all of this before this Sunday, 25th June 2006.

I assure you it's going to be fun all the way.
If you have any queries, please email me at satish.talim@gmail.com

Assumption: I am assuming that each one of you would be knowing some programming language like C or Java or VB.

Update: 42 people have registered for learning Ruby/Rails with me.


Next Post


Technorati Tags:
Blogs linking to this article

Thursday, June 15, 2006

Web Services on Rails

O'Reilly have been kind enough to give us a review copy of "Web Services on Rails" by Kevin Marshall. In recent years, web services have become increasingly useful to smaller web site developers. Thanks to standards like SOAP and XML-RPC as well as frameworks such as Ruby on Rails, developers can easily create web service clients and servers with fewer errors. This guide looks at how Ruby on Rails makes building web service clients and servers simple and fun, with plenty of working examples and code details so you can see just how everything works.
ISBN: 0-596-52796-9, 32 pages, $9.99 US, $12.99 CA
O'Reilly Link

Download this file.

Technorati Tags: ,
Blogs linking to this article