The 
Ruby Programming Language
Or,
Why are you wasting brain power?
Agneda
* The Principles of Languages
* So What?s Ruby?
* The Principles of Ruby
* Why Ruby
* Why Ruby sucks
* Resources
The Principles of Languages
* Cogito ergo sum ? Pascal.
* We think, therefore we are.
* Thinking is a most important activity for programmers.
* But how do we think?
? I think in words of specific language (probably different to yours)
? I grasp the world by a language and express myself with it
? Languages are not only tools to communicate, but also tools to think.
* But conversely, language influence thoughts
? When I use English, I am more logical and formal.
? When I use Hebrew, I speak lot more, and tend to be more expressive


* Theorem #1
Languages therefore influence human thought
? Languages are not only tools to communicate, but also tools to think.
? They influence human thought, possibly more than you think.


* But this is a talk about Ruby. Do programming languages influence human thoughts?
Programmers' Thought
* Written-down thoughts become programs. 
* When a good programmer thinks about programs, perhaps he thinks in a programming language, because natural languages are 
? too ambiguous,
? too verbose, 
? too indirect.
* Compare learning a new language to learning a new programming language (?how do I say that??)
* If programmers think in programming languages, they must influence thoughts as much as natural languages do.

* Theorem #2
"languages" include programming languages.
? We express our programming needs in them and they in turn affect the way we think and express thoughts.

* So? 
? What is the purpose of programming languages?
? Do programming languages differ in productivity?
? What makes programming languages more productive?
Purpose of Programming Languages
* Teach computers what to do.
* Describe problem to solve.
* Most importantly, express programmers thought in a form of program.

* But often forgotten: Man is not a Machine
? If you are a machine, there's no need for programming languages. You can talk to the machine directly.
A programming language should be:
A language that:
* helps our thought
* guides us to be better programmers
* makes us to enjoy programming
* but does not brainwash us ;-)
? We just want to be "influenced"*

* Read ?Babel-17? by Samuel R. Delaney.
Consider the Human Brain
Human Brain is Limited
* Men are good at
? making errors
? Creation
? Imagination
* Men are bad at
? making copies
? routine works
? fast calculation
Languages Must be Nice to Human
* To focus on Human to be productive
? At the price of machine power
* Reduce Programmers' Stress
? Stress is the enemy of Programmers
? Stress reduces productivity

How do programmers become stressed?
* By repetitive tasks
* How may times have you written for (int i=o; i < max; ++i)? ?
* By unnecessarily complex tasks
* C++ templates. ?nough said.
* By resolving problems that are not within the application domain
* Shutting up the compiler, build scripts

* i.e. By expending brain power on unnecessary things, that do not solve your main objective.






Designing a useable language
* How to make better programming experience?
By providing good usability:
? Learnability
* Useability for beginners, ?Common sense?
? Efficiency
* Performance vs. Programming Efficiency
* Users are not beginners forever
? Memorability
* Re-establishing proficiency with old code
? Errors
* Errors are the source of knowledge
* Creativity is hindered by arbitrary restrictions
? Satisfaction
* We program for money, but want to have fun as well
Which leads us to?
Is there such a wonder language that provides all this?

Long answer: Try all languages and see what fits your brain best.

Short answer: Duh, this is what this presentation is all about :)

What?s Ruby?
* Free Object-Oriented Scripting Language.

   Ruby = [Smalltalk - Unfamiliar syntax]          	 	+ Perl's scripting power                		+ Python's exception etc.                		+ CLU's iterator                			+ a lot more good things
What?s Ruby?
* Free, as in "Free Drink?.
? Developed as open source with a very open license.
? Freedom to learn from the source
? Freedom to extend and modify
What?s Ruby?
Ruby the Scripting Language:
* Scripting is programmability
* Generations of Scripting Language
? 0th Generation
Sequence of interactive commands, UUCP chat, etc.
? 1st Generation
Small, tool chest languages, shell, SED, AWK, etc.
? 2nd Generation
One step toward "usual" programming language, Perl
? 3rd Generation
Full featured programming language, Python, Ruby, Perl5
What?s Ruby?
* Ruby is as strong in scripting as Perl.
? built-in regular expression (Perl5 compatible).
? almost all equivalent functionality of Perl. Except weird features and syntax. ;-)
* can access all system calls on UNIX and Windows via a standard library
? Ruby/DL (Dynamic Loading)
? Older (explicit) libraries: syscall and Win32API
* Useful for scripting, but not limited to it.

What?s Ruby?
* Ruby's OOP Features
? Object
Everything is an object
? Class
Every class is an object
? Methods
Every procedure is a method; first-class/lambda

What?s Ruby?
* Ruby's Advanced OOP Features
? No Multiple Inheritance, but Mix-ins
Mix-in is as strong as multiple inheritance, only simpler.
? Singleton
Properties belong to specific object.
? Reflection
? Operation over meta information. Highly dynamic.
The Principles of Ruby
* Focusing on the human
* Dynamic Programming
* Principle of Least Surprise
* Principle of Succinctness
* Lightweight Language
* Choosing good names
* Embedding hidden messages
Focusing on the human

* Languages can be viewed as interface.
? Do you like to fight/play with a programming language?
* Ruby lets you focus on problems.
* Ruby lets you stay high level of abstraction.
* Ruby lets you make less errors by:
? Garbage Collection
? Extensive Class Libraries
? Arbitrary Precision Integer
? Syntax is fairly close to be ?runnable peudocode?
* When did you feel fun in programming last time?

Fun and Easy Programming
* Less frustration makes programmer feel smart and productive.
* Easy things should be easy, hard things should be possible. (Perl slogan, but we do believe it too).
* Programs should not go obfuscated without programmers' consent.
? No need to forbid obfuscation (There?s more than one way to do it)
? No need to encourage obfuscation (But some ways are better than others)
Examples: Easy on the Brain
* Method chaining:
print array.uniq.sort.reverse
* Method names can include ! and ?
ary.sort! #=> sorts in place
* Easy syntax:
exit unless mystring.include? "aura" 
* Iterators vs. loops:
files.each { |file| process(file) }
* Case usage: 
? Class names begin with a Capital letter
? Constants are ALL_CAPS
? Everything else is either a method call or a local variable

Examples: Easy on the Brain
class MyClass
	attr_reader   :name, :age
	attr_accessor :address
	alias to_s :name
end

Person = Struct.new(?person?,
				     :name, :age, :address)

Person.class 		#=> Class
rec = Person.new	#=> rec.class== Person
Examples: Blocks
* Most method calls can take a block
* It's kind of callback
* Used for Iteration, Hook, Procedure abstraction, etc.

array.each {|a| print a}

File.open(filename) {|f| f.readlines.grep(/?/) }

ary.map {|x| f(x) }.reject {|x| x<10} .inject {|sum,x| sum+=x if x%3 == 0}
Dynamic Programming
* Duck Typing
aka Dynamic typing. Based on signatures, not class inheritance.
* Dynamic Dispatch
key concept of OOP
* Dynamic Behavior
reflection, scope reopening, eval
Examples: Dynamic Programming
require ?singleton? 
Class MyClass
	include Singleton
end
o = MyClass.instance   # ?new? has been undefined

Class MyDataClass
	def <=> (other)	   # returns -1, 0 or 1
	   self.to_s <=> other.to_s
	end
	include Comperable
end

Examples: Dynamic Programming
Class scope reopening:
class String	# that?s the systems? String!
    def firstNonMatch(str, idx=0)
        i = idx
        i += 1 while self[i] == str[i]
	    return i
    end
    
	  alias trim  strip
    alias trim! strip!
end

Examples: Dynamic Programming
Object singleton class
ary = [1,2,3]  # an object
class << ary	  # it?s singleton class
	def [] (idx) # redefined
		puts ?DEBUG: accessing #{idx}?
		super
	end
end
The Principle of Least Surprise
* The supreme design goal of Ruby. Individual "surprise" differs person to person, but in general there are good surprises and bad surprises. ?least surprise" means "least bad surprise"
* POLS makes the language transparent
* POLS makes programmers happy.
* Caveat: Surprise fundamentally means Matz?s own surprise.
Examples: POLS
* What class is an object?
o.class
* Is it Array#size or Array#length?
same method ? they?re aliased
* What are the differences between arrays?
diff = ary1 ? ary2
union = ary1 + ary2
* How do I call some well known C methods?
Time.now.strftime("%Y-%b-%d")

Principle of Succinctness
* We're frustrated when 
? We feel we?re wasting time.
? We can't focus on problem itself.
? We are interrupted.
* TIME is an important factor.
* We can approximate our stress by the time we spent.
? The quicker we program, the more we program.
? The faster we finish our job, the better programmer we can be. Succinctness is Power
? Place your burden to machine's shoulders
Principle of Succinctness
* Also known as ?Principle of Least Effort?
* You write less code, you see less bugs
* You see less bugs, you can consider yourself smarter.
* You can be 10 times (or even 1000 times) more productive
* According to Fred P. Brooks: ?Programmers generate about same amount of code per day regardless of the language?
Lightweight Language
* Lightweight languages are languages that consume less Brain Power. Imagine something like Learning Curve.
* How do we measure the amount of consumed "brain power" in programming?
? Brain Power is spent when I make up the logic to solve the problem. ==> This is OK. It's a purpose of programming
? Remember the syntax of the language
? Look for reference
? Try to locate bugs
? Try to shut up compiler. Sometimes we have to modify programs for compiler's sake
Choosing Good Names
* ?Name" is Power
* If you know a true name of a thing, you have control over it.
* If you give a good name for a concept, 80% of the design is done already.
* A good name keeps motivation.
* A good name encourages us working with it.
Embedding Hidden Messages
* This is how languages can influence programmers. There's more than one way to do it, but the language can encourage some by making them comfortable than others.
* Example: Bang Methods
Some "dangerous" methods have "!" in their names. They might be faster, but you have to care about side effects. "!" reminds you of their side effect. You can avoid ugly "!" by using safer version.
Examples: Hidden Messages
* All member variables (and properties) of objects are private.
* The attr family of methods are used to specify attributes by create accessor methods:
? attr_accessor :foo
is equal to:
? def foo; @foo; end
def foo= (val); @foo=val; end
* What if the developer needs to access the ?private parts? of the object?
There are methods like:
? instance_variable_get / instance_variable_set
? instance_eval / module_eval etc.
* All these methods have long and explicit (ugly?) names. You can still do it, but by using them you are made aware of the implications.
So??

Should I or Shouldn?t I use Ruby?
Why Ruby?
* Because it's productive.
Ruby programs tend to be shorter yet readable.
* Because it's transparent.
You may want to focus on programming itself.
* Because it's free.
Not only free of charge, but freedom to use/modify/copy. Freedom to learn from its source
* Because of the Ruby community.
Helpful, without flame wars :)
Why Ruby?
* Because it's fast enough.
Fairly fast for an interpreter. Replace bottleneck by C extension.
* Because it's portable.
Portable among many platforms thanks to open source. Including GUI toolkits.
* Because it has what you need.
Enough libraries to cover maths, DBs, distributed programming, os administration, networking, serializations, graphics, web-works...
Why Ruby?
Because it's fun!

* Programming should be a fun and creative experience.
More examples: Sockets
* Basic networking:
require 'socket?
print TCPSocket.open("localhost", "daytime").read

* Web networking:
Net::HTTP::Proxy(addr, port).start(site) do |http|
    response = http.get(uri)
    File.open(filename, "w+") { |file|
        file.puts response.body
    }
end
More examples: Database
PStore: the simplest OO database: 

db = PStore.new("/tmp/foo") # open database
db.transaction do               # begin transaction
  p db.roots                       # display roots
  ary = db["root"] = [1,2,3,4]  # add to root
  ary[0] = [1,1.5]                # modify object
end                             # end transaction

* We also have PostgreSQL, MySQL, Interbase interfaces, plus Ruby/DBI database abstraction layer
Why Ruby sucks*
* Not quite as mature as perl/python
? In terms of available well-documented libraries
? On the plus side: more is available ?out of the box?
* No CPAN and the like
? but ruby gems is maturing rapidly
* ?Fast enough? but not really fast.
Syntax tree interpreter often slower than VM. This is planned for Ruby 2.0.
* Unicode support.
Currently only through UTF-8.
* Green threads only
Native threads planned for Ruby2.

* Presentation given by Matz on the future of Ruby.

The Future
Ruby2 and Rite
* Ruby2, the language
? Slightly Incompatible
? Not Just Addition
? Better Syntax
* Language syntax is taking form as ruby 1.9
* Rite, the interpreter
? Bytecode based virtual machine
? Better Performance
? Allow Native Threads and better Embedding
* Still vaporware
Ruby Resources
* http://www.ruby-lang.org/
* http://www.rubycentral.com/
* http://www.rubygarden.org/
* "Programming Ruby? - The Pragmatic Programmer's Guide, Addison Wesley, October 2000
Available online at: http://www.rubycentral.com/book
* http://poignantguide.net/ruby - Why?s (poignant) Guide to Ruby (with cartoon foxes)
* The scientific proof to why Ruby the is most loveable language :) http://bluebones.net/news/default.asp?action=view_story&story_id=81
