100% found this document useful (2 votes)
135 views

Programmer's Best Friend

The document provides an overview of Ruby and its features such as blocks, symbols, duck typing, classes and objects, inheritance, and methods. It discusses Ruby's history and how it evolved from Java and became popular as part of the LAMP stack for web development. Examples are given to illustrate Ruby concepts like classes, inheritance, and calling methods.

Uploaded by

fizous
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
135 views

Programmer's Best Friend

The document provides an overview of Ruby and its features such as blocks, symbols, duck typing, classes and objects, inheritance, and methods. It discusses Ruby's history and how it evolved from Java and became popular as part of the LAMP stack for web development. Examples are given to illustrate Ruby concepts like classes, inheritance, and calling methods.

Uploaded by

fizous
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 98

Programmer’s Best Friend

It’s 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
• Kon’nichi wa, Ruby
So…let’s 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 language’s 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 don’t you just believe that the problem
was in the Java language as a language?
• Strict typing.
• Complex architecture.
• More skilled engineers too.

• Anyway, it’s 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.

It’s 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!!
Kon’nichi 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
It’s a language..We MEAN it

Read the following aloud to yourself.

5.times {print “Ruby!"}

5 times print “Ruby!”.


Once again, may be it’s a coincidence.

exit unless "restaurant".include? "aura“

Exits unless the word “restaurant” includes


the word “aura”
Once again, may be it’s 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.
Objects…Everything Is An Object

• Smalltalk….everything is an object.
• Isn’t 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
It’s 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…

IT’s a DUCK
It’s 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..it’s 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 # I get that it’s an integer.

- Instead of
Int x = 5
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.new”batoot”
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 # error
batoot.eat # 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… It’s same as Java….
Objects..More Independent Batoot
We didn’t see everything yet…..

class Duck
attribute_accessor: enemy # read & write
attribute_reader: food # read only
attribute_writer: mood # set only
end

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 polymorphism…Same as Java
Which means:

class Animal
def initialize(name)
print name
end
end
class Duck < Animal
def initialize
print “duck’s name is”
super
end
end
duck = Duck.new(“Batoot”) # “duck’s name is Batoot”
Objects..Batoot’s 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 passing…Ruby, 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 isn’t 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 Misèrables

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 # Fixnum
32.Kind_of?Numeric # true
32.instance_of?Fixnum # true

or you can check if it has a certain method


32.respond_to? '+' # true
12.respond_to? 'length' # false
Ruby has Reflection…More to come.

For classes
Duck.superclass #Animal
Duck.ancestors
#returns parent classes and included modules
# [Animal, CruelBehavior, Object, Kernel]

Duck.public_instance_methods
Duck.singelton_methods
# class (static) methods
Duck.constants
Ruby has Reflection…More 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' => “fizo’s 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

Why’s (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