Showing posts with label ruby examples. Show all posts
Showing posts with label ruby examples. Show all posts

Monday, January 7

Ruby on Rails Arrays and Hashes

Download the Examples
Arrays

Ruby has Arrays and Hashes to store/collect the objects.
And these objects are accessed using an index.

Array:
1. It is an ordered collection of objects.
2. Indexed with integers.

How to create an Array?
Answer is there are three different ways to create an array.
# Way 1 :
a1 = []

# Crosscheck whether we created the array "a1".
puts "a1 is an #{a1.class}"

# Way 2 :
a2 = [1,2,3]

# Crosscheck whether we created the array "a2".
puts "a2 is an #{a2.class}"

# Way 3 :
a3 = Array.new

# Crosscheck whether we created the array "a3".
puts "a3 is an #{a3.class}"


# Note:
# --> The array holds the objects within square brackets.
# --> The multiple objects separated with commas.
# --> The array holds different objects (int, float, string...).
# --> Way 1, creates an empty array.
# --> Way 2, creates an array with few objects defined/collected.
# --> Way 3, creates an empty array using ".new" operator/method.
# --> At any point to check whether we created array's or not, we can use ".class".

Exercise:
Well following are the built in methods that we can apply on to arrays.
&, *, +, -, <<, <=> , ==, [], [], []=, abbrev, assoc, at, clear, collect, collect!, compact , compact!, concat , dclone , delete, delete_at, delete_if, each, each_index, empty? , eql?, fetch , fill, first, flatten , flatten!, frozen? , hash include?, index , indexes, indices, initialize_copy , insert, inspect , join, last, length, map , map!, new, nitems , pack , pop, pretty_print, pretty_print_cycle, push , quote, rassoc, reject , reject!, replace, reverse, reverse! , reverse_each , rindex , select, shift, size , slice, slice!, sort , sort!, to_a , to_ary , to_s , to_yaml, transpose, uniq , uniq! , unshift, values_at, yaml_initialize, zip , .

Download the Examples

Hashes :


Ruby has Arrays and Hashes to store/collect the objects.
And these objects are accessed using an index.


# How to create an Hash?
# Answer is there are three different ways to create an Hash.
# Way 1 :
h1 = {}

# Crosscheck whether we created the Hash "h1".
puts "h1 is a #{h1.class}"

# Way 2 :
h2 = {
"Object1"=>"First Object",
"Object2"=>"Second Object"
}

# Crosscheck whether we created the Hash "h2".
puts "h2 is a #{h2.class}"

# Way 3 :
h3 = Hash.new

# Crosscheck whether we created the Hash "h3".
puts "h3 is a #{h3.class}"


# Note:
# --> The hash hold objects within curly braces.
# --> The Key and Value pair forms an object in Hash.
# --> The multiple objects separated with commas.
# --> The hash holds different data types.
# --> Way 1, creates an empty Hash.
# --> Way 2, creates an Hash with few objects defined/collected.
# --> Way 3, creates an empty Hash using ".new" operator/method.
# --> At any point to check whether we created Hash or not, we can use ".class".

Exercise on Hashes:

==, [], [], []=, clear, default, default=, default_proc, delete, delete_if, each, each_key, each_pair, each_value, empty?, fetch, has_key?, has_value?, include?, index, indexes, indices, initialize_copy, inspect, invert, key?, keys, length, member?, merge, merge!, new, pretty_print , pretty_print_cycle, rehash, reject, reject!, replace, select, shift, size, sort, store, to_a, to_hash, to_s, to_yaml, update, value?, values, values_at, yaml_initialize

Download the Examples
The zip file contains examples on Creating Arrays and Hashes, Methods implemented on arrays.
Note:
  1. Please comment/un comment the wanted/un necessary puts, for better understanding.

Tuesday, December 18

Ruby on Rails simple examples & String Class

After the previous post, hope you successfully installed the ruby on to your machine and ready to speed up our tutorials.
Now let us see a simple math example, factorial function. How do we write a program that would calculate the factorial value of integer that we would pass.
Basically factorial is:
n! = 1                (when n==0)
   = n * (n-1)!       (otherwise)
  • The simple logic that we are aware is, factorial is nothing but a recursive function call.
It means we write a function and will be calling the same function within that. So this would look something like this:



If you notice here there are lot of points to carry with us,
  • You may notice the repeated occurrence of end.
  • You may also notice the lack of a return statement.
  • It is not needed because a ruby function returns the last thing that was evaluated in it. Though use of a return statement is permissible but it is not necessary here.
  • ARGV is an array which contains the command line arguments, and to_i converts a character string to an integer.
Experiments:
  1. What happens if I pass string as argument instead of integer?
  2. At the line “12”, replace the double quote with single quote and see what happens?
Download or View on Scribd

Ruby String Class:

A String object holds and manipulates an arbitrary sequence of bytes, typically representing characters. String objects may be created using String::new or as literals.

Because of aliasing issues, users of strings should be aware of the methods that modify the contents of a String object.

· Methods with names ending in ``!’’ modify their receiver.

· Methods without a ``!’’ return a new String.

Ruby deals with strings as well as numerical data. A string may be double-quoted ("...") or single-quoted ('...').

· A double-quoted string allows character escapes by a leading backslash, and the evaluation of embedded expressions using #{}.

· A single-quoted string does not do this interpreting; what you see is what you get.

Examples:

If you had done the above mentioned experiments, it is easy to understand the above two points. The difference between the double and single quotes around a string. There are plenty of methods that ruby offers, they come very handy!

capitalize:

str.capitalize => new_str

This method turns the first letter of the string to upper case.

"ruby".capitalize    #=> "Ruby"

Methods with names ending in ``!’’ modify their receiver.

capitalize!:

str.capitalize! => str or nil
Modifies str by converting the first character to uppercase and the remainder to lowercase. Returns nil if no changes are made.

   a = "hello"
   a.capitalize!   #=> "Hello"
   a               #=> "Hello"
   a.capitalize!   #=> nil
Find more examples and other methods ruby supports.
Download or View on Scribd

Tuesday, December 11

Ruby on Rails Installing Ruby

Though you continue to work/experiment more on the online ruby editor, today we see how we would install the ruby on windows OS.
Recollect "Ruby is portable, which means can be installed on all OS's possible"

Ruby Installer for Windows. Download the executable ruby186-25.exe and double-click this file to install Ruby on your PC. (Accept all the defaults.)
Once you have installed your Ruby software, the System Environment Variable path is already set to point to the bin folder of Ruby. The installation also includes the First Edition of Programming Ruby book and the SciTE editor.

Just recollect what we had done and what's the Ruby Environment looks like.

Assuming that you installed Ruby in the folder c:/ruby, then the installation creates a number of sub-folders. See the list below.

c:/ruby/bin : Here the Ruby executables (including ruby and irb) have been installed.
c:/ruby/src : Here you get the Ruby source code.
c:/ruby/lib/ruby/gems : Here are the Ruby-Gems.
c:/ruby/lib/ruby/1.8 : Here you'll find program files written in Ruby. These files provide standard library facilities, which you can require from your own programs if you need the functionality they provide.
c:/ruby/lib/ruby/1.8/i386-mswin32 : Here you find architecture-specific extensions and libraries. These files are C-language extensions to Ruby; or, more precisely, they are the binary, runtime-loadable files generated from Ruby's C-language extension code, compiled into binary form as part of the Ruby installation process.
c:/ruby/lib/ruby/site_ruby : Here you store third-party extensions and libraries. This include your own code or some third party.
c:/ruby/samples/RubySrc-1.8.6/sample : Well, here you will find some sample Ruby programs.

From now we can also execute ruby snippets on the locally installed SciTE editor.
Open the Editor: start/Programs/Ruby-186-25/SciTE.
Press F8 to open an output window.

Create a folder named, say. rubyexamples on your C:\ and will keep all our programs in this folder. Let us repeat the our first program, that we had done yesterday online. That is

puts "Hello World!"

Now save the file as "hello.rb" under c:\rubyexamples folder. Note all ruby source files have the .rb extension.

Pressing on F5 would execute the program and outputs the string "Hello World!" on right side window.

  1. # hello.rb
  2. puts 'Hello'

Alternatively you can also type command "ruby hello.rb" to execute the hello.rb file.

Having installed the ruby on local system now repeat the yesterdays examples and practice more for better understanding.

Download the pdf version of Installing Ruby post.


Monday, December 10

Ruby on Rails Learning through examples

What ruby is used for?
Let us recollect the statement:
Ruby is "an interpreted scripting language for quick and easy object-oriented programming".
Ruby is used for many kind of applications be it writing automation scripts and run on your local pc's, or developing automation tools, or Website, or Blogs, Web Application or web based products and the list goes on...

We here pick up basics of Ruby just enough to get going with Rails and start developing simple websites and web applications.
All the things that we had said about ruby in earlier post What is Ruby? will be discussed in coming posts.
Learning through Examples:

Before even going for installing the ruby in your desktop, let us experiment on ruby with small examples and work/execute them here online.

This is our play ground:
This is called interactive ruby shell and we find ">>" similar to command/shell prompt. Now let's start with famous example of printing out "Hello World!" statement.
  1. type puts "Hello World!" >> puts "Hello World!"
  2. then click "Enter" button
  3. Now you would find the expected returned
  • >> puts "Hello World!"
  • Hello World!
    => nil
So puts is the ruby way of printing the things to console/prompt. The first line means to print the string within the quotes(i.e. Hello World!). Your would also find "=> nil" displayed in the next line of the Hello World! statement, puts always returns nil, which is Ruby’s absolutely-positively-nothing value.

Going on to the next example:
  • Ruby has simple syntax.
  • Ruby is dynamically typed.
  • Ruby needs no variable declarations.
  • Ruby operators are also methods.
Now I want to do simple math. Based on the above points,
to add two integers just type : 4+2
to subtract two integers just type : 4-2
to multiply two integers just type : 4*2
to divide two integers just type : 4/2
You can check out with other types also. Need not be of same type, since ruby is dynamic language at the run time they would be evaluated.
for example you type 2.0+3 and see for yourself.

Coming on to the variable declaration, ruby does not require the variable declarations. Let us the see this point also:
you type
>> a=5
=>5
>>b=2.0
=>2.0
>>c=a+b
=>7.0
As you see we have not declared the variables a,b,c and what type they hold. All these variables are evaluated at the run time and treated accordingly.
Ruby treat the operators(+,-,*,/,%...) as just like methods, which is conceptually derived from Smalltalk.

Download the pdf version of Learning Through Examples.
The pdf includes:
  • Useful links
  • Duck typing explained with example.
  • Examples with appropriate comments and explanation.
  • Ruby resources links.