You are on page 1of 98

Programmers Best Friend

Its History

Why We Are Here? Agenda

To talk about the beautifulness of Ruby.


Beauty&The Beast.
Start a debate.
The debate turns to be a fight.

Disappointed?

Can you just tell us what it will be


about?
We will get a quick overview about how
things were going before.
How to decide my language-friend
Konnichi wa, Ruby

Solets start the session in peace


please

Java EE which turns later to be Java2E

Focused on enterprise
integration, transaction
management and other
back-end processing.
Others were considered just
toys.

The killer

The second half of

Shift to the Web:


Media and e-commerce Web sites.
Business applications including CRM,
ERP, reporting, document management,
etc

servlets and JSPs.


Ignoring the RESTful nature of the Web.
driving a general purpose platform.

LAMP-like architecture built on top


of the C languages eco-system of
libraries and tools started
becoming the most popular
platform for developing Web
applications.

Why?

LAMP
Domain Specific to the web.
Fit like a glove to the web paradigm.
We started to hold the market share.

LAMP
Did I forget to say that the successful Yahoo
was Perl?
Then forgive me
PHP packages including Wordpress, Drupal,
mediaWiki, osCommerce, SugarCRM, and
more

Java. included Java Server Faces, Struts,


Spring MVC and others.

Why dont you just believe that the problem


was in the Java language as a language?
Strict typing.
Complex architecture.
More skilled engineers too.
Anyway, its business

Microsoft worked to add a large


amount of languages
including Cobol, Eiffel, Ruby,
Python, and others. Not just
C# and VB..

I am making a plan to check


if there is enough budget for
my visual studio.NET next
release.
I feel Heavy

My Grandma Taught Me
The tale of Mr. Bangar

LAMP
Communities driven projects.
Users develop the language.

Its Agility.

Some started to import dynamic


languages on top of their VM. Sun invests
in Jython and Jruby.
With Microsoft on one side and the Java
competitors on the other, each vendor set
out to develop their own dynamic
languages strategy.

Excusa
What about the functional programming
languages?
Lisp, Haskell, Erlang..etc
Or you never hear about them?
Say it..say it..say it.

Who Wins?

A long endless debate..

My Grandma Taught Me
What I should do?
I should know what fit best for my
requirements

Decision!!

Cost?
Stability, reliability, security?
complexity?
Support?
Performance?
Environment?

System Calls on IIS

System Calls on Apache

Care About Reliability?


VM are multi-threaded, failure may crash
the system.
Scripting languages feature multi-process
architecture. Recycling processes after a
set time to prevent memory leaks
Remember Facebook? Do u feel that
system is down in order to add a new
feature?? System needs no re-packaging.

Everyone cares about the machine!!!


What about me? I feel lonely, Nobody
cares about my time!!

Konnichi wa, Ruby

Ruby is designed to make


Programmer Happy
Yukihiro Matsumoto(Matz) creator of Ruby

Released 1995
It was C based single pass interpreter till
version 1. 8 .6
Version 1.9, December 2007, it becomes
virtual machine based.
Many other Implementations exist:
JRuby
IronRuby
Rubinius

Its a language..We MEAN it


Read the following aloud to yourself.
5.times {print Ruby!"}
5 times print Ruby!.

Once again, may be its a coincidence.


exit unless "restaurant".include? "aura

Exits unless the word restaurant includes


the word aura

Once again, may be its a coincidence.


['toast', 'cheese', bread'].each {
|food| print food.capitalize
}

With the words toast, cheese, and bread:


take each food and print it capitalized.

Things We Need to Know


Blocks:
Surrounded by do..end, sometimes surrounded
by {..}
Symbols:
The thing called.They are variable whose names
are their values.
They are immutable.
:a, :b, :session
Only one copy exist of a certain symbol value
used very widely in hashing.

ObjectsEverything Is An Object

Smalltalk.everything is an object.
Isnt java object oriented?
Ruby inherits this feature from the
Smalltalk.
Note: sometimes blocks are not objects

Everything Is An Object

Remember our first example?


5.times {print Ruby!"}
-10.abs
#10
I love Ruby.length
#16
nil.nil?
#true

Its Time For A Puzzle


If I tell you that I have something at home
that does the following:
1.It talks like a duck.
2.It walks like a duck.
Can you guess what I have?

Congratulations, You get it


ITs a DUCK

Its Time for Another Puzzle to Test your


IQ
If I tell you that I have something at home
that does the following:
1. It is an animal.
2. It has two legs.
3. Its name is batoot
Can you guess what I have?

Two puzzles with the same answer.


I knew it was a duck because I knew what it can
do.
I knew it was a duck because I knew what it is.

MORAL of the Tale


Duck Typing..if something talks like a duck and
walks like a duck, then to the interpreter..its a
duck.

Duck..The Good & The Bad.

It ate my IDE. Bad duck


It is really fast to build my tests. Good duck
Easy to re-factor, away from the complexity
of relationships. Good duck

A Duck Tale

class Duck
##class body goes here
end

Let the Duck Eat


class Duck
def eat
#method body goes here
end
end

Objects..Initializing Method
class Duck
def initialize
# I will be called
# when a new object of type animal
# is created

end
end

Microsoft has Something to Announce

In my next release.. I am going to support


dynamic typing.
- So you type:

var x = 5
- Instead of

Int x = 5

# I get that its an integer.

Congratulations .NET.
Finally you have a dynamic typing.

Ruby has also dynamic typing.


But Ruby is the most dynamic language.

My Grandma Taught Me
Teenage Shirt

Oh. We Need Our Duck To Sleep


class Duck
def eat
end
end
..

class Duck # reopen Duck class


def sleep
end
end
Duck has both methods now

Objects..Birth of Batoot

batoot = Duck.new
batoot = Duck.new()
batoot = Duck.newbatoot
batoot = Duck.new(batoot)

Objects..Even After Batoot is Born


class Duck
def eat
end
end
batoot = Duck.new
class Duck
def sleep
end
end

batoot can sleep


batoota = Duck.new
Makes them a cool couple.

My Grandma Taught Me
The tale of the man & ablutions
When we say it worked with me..

Objects..Batoot Needs to Be Unique


class Duck
def eat
end
end
batoot = Duck.new
def batoot.sleep
#method body goes here

end

Objects..Batoot Needs Some Privacy


class Duck
def eat
end
private
def breath
end
end
batoot = Duck.new
batoot.breath
batoot.eat

#
#

error
seems correct

Methods by default are public

Objects..Needs Weapons
class Duck
def fight(something)
if something == @enemy bite
end
private
def bite
end
end

Instant variables are private.

Objects..Getters & Setters


Class Duck
def enemy =(enemy)
@enemy = enemy
end
def enemy
return @enemy
end
end
usage:
batoot = Duck.new
batoot.enemy = ma7zooz
batoot.enemy = (ma7zooz)
batoot.enemy # ma7zooz

Hey dude Its same as Java.

Objects..More Independent Batoot


We didnt see everything yet..
class Duck
attribute_accessor: enemy
attribute_reader: food
attribute_writer: mood
end

# read & write


# read only
# set only

This is what we call Uniform Access Principle.


Only one way to access instance variables.

Objects..Batoot Inherits from Others


Something wrong about C++ ?
Java did it for me..
No multiple inheritance.
By default they all inherit from Object

And same as Ruby.

Objects..By the end Batoot is an


Object
Class Duck
end
Duck.superclass

Object

I hope it can be an animal


class Duck < Animal
end
Duck.superclass
#

Animal

Objects..Does it have to Sleep like All


Animals?
No need to talk about polymorphismSame as Java
Which means:

class Animal
def initialize(name)
print name
end
end
class Duck < Animal
def initialize
print ducks name is
super
end
end
duck = Duck.new(Batoot) # ducks name is Batoot

Objects..Batoots Interfaces

Java had something that was called


Interface.

We Can Buy mixins to Batoot


Module CruelBehavior
def attack
bite
end
end
class Duck
include CruelBehavior
end
batoot = Duck.new(batoot)

# Batoot can attack


# anyone of us now

Remember the Enumerable module. It adds method each for


classes like Array and Hash.

Enough for classes.

What about Methods!!

Smalltalk uses message passingRuby, has


this feature too.
dot
send
call

Methods..calling
class Duck
def eat(food)
end
end
duck = Duck.new
duck.eat(meshmesh)
duck.send(eat,meshmesh)
eating = cat.method(eat)
eating.call(meshmesh)

Methods

What if I am not sure about the


arguments?
Well, Ruby has an answer for this

Methods
Class Duck
def eat(*food)
# when variables are received,
# they are stored in an array named food
end

end
batoot = Duck.new
batoot.eat(dust, paper, cucumber)
# or
batoot.send(eat, dust, paper, cucumber)

Methods
Arrays expand to match the arguments
def four(a,b,c,d)
puts #{a}, #{b}, #{c}, #{d}
end
four(1,2,3,4) # => 1,2,3,4
four(1,2,*['a','b']) # => 1,2,a,b
four(*(5..8).to_a) #=> 5,6,7,8

Methods
Default arguments!!!
Return values no need to specify a return
statement. if u left it, ruby will return the last
sentence
I can return multiple values through methods..(
tasty isnt it)

Methods
def min_max(a, b)
return a,b if a < b
b, a
end
min, max = min_max(7,2)
# min now equals 2
# max now equals 7
def swap(a, b)
b, a # similar to saying: a, b = b, a
end

Les Misrables
Our duck Batoot is still feeling miserable,
Everyone is teasing and messing with it.
They call methods not defined for Batoot.
A possible solution is to add a recorder and
see how people with Batoot.

method_missing
This method acts as a trap for undefined methods
Used to create methods on the fly!
class Recorder
@@calls = []
def method_missing(name,*args)
@@calls << [name,args]
end
def play_back(obj)
@@calls.each do |call|
obj.send(call[0], *call[1])
end
end
end

batoot = Duck.new
batoot.capitalize!
batoot.playback

prints Batoot.

#stored calls were replayed on the string

Batoot Needs Supervision


Batoot is getting older and he wants to play with
his peers.
His peers are naughty and they teach it bad
things.
How can I let Batoot play with him, gain
experience while supervising it?

Ruby defines a very useful callback


functions for some events.
method_added
# called whenever a method is added to a class
# or a module

inherited
# called on a class whenever it is subclassed

included
# called on a module whenever it is included

Java has Reflection.

So does Ruby

Reflection?
It means the ability to lookup the structure of
the program in run time

Ruby has Reflection.


You can check the methods of an object
[1,2,3].methods.select{|m|m==send}
# [send]

or its class (or ancestor class)


32.class
32.Kind_of?Numeric
32.instance_of?Fixnum

# Fixnum
# true
# true

or you can check if it has a certain method


32.respond_to? '+'
12.respond_to? 'length'

# true
# false

Ruby has ReflectionMore to come.


For classes
Duck.superclass
Duck.ancestors

#Animal

#returns parent classes and included modules


# [Animal, CruelBehavior, Object, Kernel]

Duck.public_instance_methods
Duck.singelton_methods
# class (static) methods

Duck.constants

Ruby has ReflectionMore to come.


For System
ObjectSpace.each_object do |obj|
# iterate over all the objects in the system

end

Java Has Map


import java.util.*;
public class PrintEnv {
public static void main(String[] args) {
Map map = System.getenv();
for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry e = (Map.Entry) it.next();
System.out.println(String.format("%s: %s", e.getKey(),
e.getValue()));
}
}
}

Ruby has Hash

Hashes
Curly braces
{ 'name' => batoot',
location' => fizos home,
status' => single' }

Blocks
Really Powerful...they add a great value of
Functional programming to Ruby.
(which is a characteristic of dynamic languages)

function new_scanner (word)


temp_function = function (input)
scan_for_text (input, word)
end function
return temp_function
end function

Blocks
Need to Print ducks names
ducks.each{|duck| print duck.name}
#prints batoot, soso, lolo, toto

Finding batoot
batoot = Ducks.select{|duck|duck.name==batoot}
Change the array of ducks to array of ducks names
ducks.collect!{|duck|duck.name}

Blocks
Need to environment variables
ENV.each{|k,v| puts #{k}:#{v}}

Is that it!!!!!!!!!!

Enough is Enough

Readings

Whys (Poignant) Guide to Ruby

Readings

Resources

http://poignantguide.net/ruby/
www.railsenvy.com
www.rubyonrails.org
http://oldmoe.blogspot.com
http://andigutmans.blogspot.com
Rails for Java Developers

You might also like