Ruby A Programmer's First Look 5/23/2016 9:16:06 1

Download Report

Transcript Ruby A Programmer's First Look 5/23/2016 9:16:06 1

Ruby
A Programmer's First Look
5/23/2016 9:16:06
PM
Tim Zappe, October 6th, 2006
1
Kon’nichi wa, Ruby
Ruby is a reflective, object-oriented programming language. It combines syntax
inspired by Perl with Smalltalk-like object-oriented features, and also shares
some features with Python, Lisp, Dylan and CLU. Ruby is a single-pass
interpreted language. Its main implementation is free software distributed under
an open-source license.
The language was created by Yukihiro "Matz"
Matsumoto, who started working on Ruby on
February 24, 1993, and released it to the public in
1995. "Ruby" was named after a colleague's
birthstone. As of September 2006, the latest stable
version is 1.8.5. Ruby 1.9 (with some major
changes) is also in development.
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
2
Why Ruby? Why Now?
I think we often become involved with a language because
of a project we can attempt to achieve. Very seldom are we
able to simply build something in a language without a
specific goal in mind. In my case, Ruby powers a web frame
work called Rails. If it weren’t for David Heinemeier
Hansson’s decision to power Rails with Ruby, I wouldn’t be
talking about it today. Even with my somewhat limited
exposure to Ruby, my thanks go out to both David and Matz
for all of their hard work.
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
3
Ruby Features
•
•
•
•
•
•
•
•
•
•
•
•
•
•
object-oriented
four levels of variable scope: global, class, instance, and local
exception handling
iterators and closures (based on passing blocks of code)
native, Perl-like regular expressions at the language level
operator overloading
automatic garbage collecting
highly portable
cooperative multi-threading on all platforms using green threads
DLL/shared library dynamic loading on most platforms
introspection, reflection and meta-programming
large standard library
supports dependency injection
continuations and generators
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
4
Ideals
Ruby is a language of careful balance. Matsumoto
blended parts of his favorite languages (Perl, Smalltalk,
Eiffel, Ada, and Lisp) to form a new language that
balanced functional programming with imperative
programming.
He has often said that he is “trying to make Ruby
natural, not simple,” in a way that mirrors life.
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
5
Growth
Since its public release in 1995, Ruby has drawn devoted coders worldwide. In 2006,
Ruby achieved mass acceptance. With active user groups formed in the world’s major
cities and Ruby-related conferences filled to capacity.
Ruby-Talk, the primary mailing list for discussion of the Ruby language has climbed to
an average of 200 messages per day.
The TIOBE index, which measures the growth of programming languages, ranks Ruby
as #13 among programming languages worldwide. Citing its growth, they predict,
“Chances are that Ruby will enter the top 10 within half a year.” Much of the growth is
attributed to the popularity of software written in Ruby, particularly the Ruby on Rails
web framework.
Ruby is also totally free. Not only free of charge, but also free to use, copy, modify, and
distribute.
Current Ratings: http://www.tiobe.com/tpci.htm
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
6
Everything’s an Object
Initially, Matz looked at other languages to find an ideal syntax. Recalling his search,
he said, “I wanted a scripting language that was more powerful than Perl, and more
object-oriented than Python.”
In Ruby, everything is an object. Every bit of information and code can be given their
own properties and actions. Object-oriented programming calls properties by the
name instance variables and actions are known as methods. Ruby’s pure objectoriented approach is most commonly demonstrated by a bit of code which applies an
action to a number.
5.times { print "We *love* Ruby -- it's outrageous!" }
In many languages, numbers and other primitive types are not objects. Ruby follows
the influence of the Smalltalk language by giving methods and instance variables to
all of its types. This eases one’s use of Ruby, since rules applying to objects apply to
all of Ruby.
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
7
Ruby’s Flexibility
Ruby is seen as a flexible language, since it allows its users to freely alter its parts.
Essential parts of Ruby can be removed or redefined, at will. Existing parts can be
added upon. Ruby tries not to restrict the coder.
For example, addition is performed with the plus (+) operator. But, if you’d rather use
the readable word plus, you could add such a method to Ruby’s builtin Numeric
class.
class Numeric
def plus(x)
self.+(x)
end
end
y = 5.plus 6
# y is now equal to 11
Ruby’s operators are syntactic sugar for methods. You can redefine them as well.
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
8
Blocks
Ruby’s block are also seen as a source of great flexibility. A programmer can attach a
closure to any method, describing how that method should act. The closure is called a
block and has become one of the most popular features for newcomers to Ruby from
other imperative languages like PHP or Visual Basic.
Blocks are insipired by functional languages. Matz said, “in Ruby closures, I wanted to
respect the Lisp culture.”
search_engines =
%w[Google Yahoo MSN].map do |engine|
"http://www." + engine.downcase + ".com"
end
In the above code, the block is described inside the do ... end construct. The map
method applies the block to the provided list of words. Many other methods in Ruby
leave a hole open for a coder to write their own block to fill in the details of what that
method should do.
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
9
Seeing is Believing
While Ruby often uses very limited punctuation and usually prefers English
keywords, some punctuation is used to decorate Ruby. Ruby needs no
variable declarations. It uses simple naming conventions to denote the scope
of variables.
var could be a local variable.
@var is an instance variable.
$var is a global variable.
These sigils enhance readability by allowing the programmer to easily identify
the roles of each variable. It also becomes unnecessary to use a tiresome
self. prepended to every instance member.
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
10
More…
•
•
•
•
•
•
Ruby has exception handling features, like Java or Python, to make it easy to
handle errors.
Ruby features a true mark-and-sweep garbage collector for all Ruby objects. No
need to maintain reference counts in extension libraries. As Matz says, “This is
better for your health.”
Writing C extensions in Ruby is easier than in Perl or Python, with a very elegant
API for calling Ruby from C. This includes calls for embedding Ruby in software,
for use as a scripting language. A SWIG interface is also available.
Ruby can load extension libraries dynamically if an OS allows.
Ruby features OS independent threading. Thus, for all platforms on which Ruby
runs, you also have multithreading, regardless of if the OS supports it or not,
even on MS-DOS!
Ruby is highly portable: it is developed mostly on GNU/Linux, but works on
many types of UNIX, Mac OS X, Windows 95/98/Me/NT/2000/XP, DOS, BeOS,
OS/2, etc.
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
11
Write the Language
Many of Ruby’s parts of speech have visual cues to help you identify them.
Punctuation and capitalization will help your brain to see bits of code and
feel intense recognition.
•
•
•
•
•
•
•
•
•
Variables
Numbers
Strings
Symbols
Constants
Methods
Class Methods
Global Variables
Instance Variables
5/23/2016 9:16:06
PM
•
•
•
•
•
•
•
•
•
Class Variables
Blocks
Block Arguments
Ranges
Regular Expressions
Arrays
Hashes
Operators
Keywords
Ruby, a Programmer’s First Look
12
In the Beginning
Variables
Any plain lowercase word is a variable in Ruby. Variables may consist of
letters, digits, and underscores
x, y, peterson06, and amazing_ruby_presentation are examples
Numbers
Integers and floats are both available in Ruby. In addition, underscores and
scientific notation are available.
42, 10.13, -1234, 12.043e-04, and 53_000_000 are examples
Strings
Strings are any sort of characters (letters, digits, punctuation) surrounded by
quotes. Both single and double quotes can be used.
“4000”, ‘Las Vegas or bust’, and “Exclusive or was a the answer!” are examples
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
13
Specialty Items
Symbols
Symbols are words that look just like variables. Again, they may contain
letters, digits, or underscores. But they start with a colon.
Symbols are lightweight strings. Usually, symbols are used in situations where
you need a string but you won’t be printing it to the screen.
:a, :xor, and :mister_fancy_pants are examples
Constants
Constants are words like variables, but constants are capitalized. If variables
are the nouns of Ruby, then think of constants as the proper nouns. Much like a
real proper noun in the English language, once a Constant is defined it cannot
be changed.
First_Snowfall, The_Empire_State_Building, and Crested_Butte are examples
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
14
Action!
Methods
Methods are like the verbs in Ruby. They are indicated by a dot. Methods can
be strung together and both question marks and exclamation points maybe
used in method names.
Examples:
ruby_presentation.attend
ruby_presentation.attend.sleep
ruby_presentation.is_interesting?
ruby_presentation.speaker( TimZappe )
print “See, no dot.”
Class Methods
Like the methods described above (also called instance methods), class
methods are usually attached after variables and constants. Rather than a dot,
a double colon is used.
Presentation::next( “Intro to Prolog” ) is an example
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
15
All about scope
Global Variables
Variables which begin with a dollar sign are global.
$x, $mips, and $intel_is_complicated are examples
Instance Variables
Variables that begin with an at symbol are instance variables and are often
used to define the attributes. For example, you might provide Ruby with the
length of ruby_presentation by setting the @duration variable. Instance
variables are used to define characteristics of a single object.
@duration and @coolness are examples
Class Variables
Variables that begin with double at symbols are class variables and are also
used to define attributes. Instead of defining a single attribute of a
ruby_presentation, it can be used to define everything that is a Presentation.
@@location and @@heckler are examples
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
16
Blocks
Blocks
Any code surrounded by curly braces is a block.
3.times { print “Beatlejuice” } is an example
Curly braces can also be traded for do and end.
loop do
print “Look Ma!”
print “No curly braces!”
end
Block Arguments
Block arguments are a set of variables surrounded by pipe characters and
separated by commas. Block arguments are used at the beginning of a block.
Classmates.each do | name, hand |
print “Thanks for coming, ” + name.capitalize
hand.shake
end
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
17
Ranges and Regular Expressions
Ranges
A range is two values surrounded by parentheses and separated by an ellipsis
(in the form of two or three dots).
(1..3) is a range, representing the numbers 1 through 3.
('a'..'z') is a range, representing a lowercase alphabet.
(0...5) represents the numbers 0 through 4.
Regular Expressions
A regular expression (or regexp) is a set of characters surrounded by slashes.
/ruby/, /[0-9]+/ and /^\d{3}-\d{3}-\d{4}/ are examples.
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
18
Arrays and Hashes
Arrays
An array is a list surrounded by square brackets and separated by commas.
[1, 2, 3] is an array of numbers.
[’PHP', ’Perl', ’Python'] is an array of strings.
Hashes
A hash is a dictionary surrounded by curly braces. Dictionaries match words
with their definitions. Ruby does so with arrows made from an equals sign,
followed by a greater-than sign.
{’sll' => ’shift logic left', ’addi' => ’add immediate’} is an example.
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
19
Operators and Keywords
Operators
Here are the Ruby operators -- know some and look up others.
** ! ~ * / % + - & << >> | ^ > >= < <=
<=> || != =~ !~ && += -= == === .. ... not and or
Keywords
Here are the Ruby keywords -- same catch as above.
alias and BEGIN begin break case class def defined do else elsif END
end ensure false for if in
module next nil not or
redo rescue retry
return self super then true undef unless until when while yield
5/23/2016 9:16:06
PM
20
Code Examples
# "Hello, World!" in Ruby
puts "Hello, world!"
# Sample Class
class KaraokeSong < Song
@@plays = 0
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
@plays = 0
end
def play
@plays += 1
@@plays += 1
"This song: #@plays plays. Total #@@plays plays."
end
end
Greeter Class
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
21
Surprises
• Only false and nil evaluate to false
• A float must be defined with a decimal and a
following digit, 99. is considered a float.
• When calling a character you might find the
ASCII value being returned. Use either a
substring operation or a character typecast to
obtain the character value.
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
22
Real Life Examples
•
•
•
•
•
•
Ruby on Rails
SketchUp from Google
RubyGems (Ruby Package Manager)
Interactive Ruby Shell (irb)
The Ruby Application Archive lists 1499 projects
Watir (IE testing application)
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
23
# Output "I love Ruby"
say = "I love Ruby"
puts say
Learn Ruby
•
•
•
•
•
•
•
•
•
•
•
•
# Output "I *LOVE* RUBY"
say['love'] = "*love*"
puts say.upcase
# Output "I *love* Ruby"
# five times
5.times { puts say }
http://tryruby.hobix.com/ My Favorite
http://www.ruby-lang.org/en/documentation/quickstart/
http://www.rubycentral.com/book/ Matz’s Book
http://sitekreator.com/satishtalim/index.html
http://www.ruby-lang.org/ Ruby’s Home Page
http://www.ruby-doc.org/
http://www.ruby-forum.com/
http://www.rubywizards.com/
http://raa.ruby-lang.org/
http://ruby.cenophobie.com/rubycheat.php Cheatsheet from today
http://www.zenspider.com/Languages/Ruby/QuickRef.html
http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/
5/23/2016 9:16:06
PM
Ruby, a Programmer’s First Look
24