|
Softpanorama |
May the source be with you, but remember the KISS principle ;-)
|
| Recommended Papers | Reference | FAQs | |||
| Iterators | Coroutines | Exceptions | Namespaces | Humor | Etc |
Ruby is an interesting Perl derivative with some OO-bent created by Yukihiro Matsumoto (aka "matz").
Ruby's syntax and design philosophy are heavily influenced by Perl. It has a lot of syntactic variability. Statement modifiers (if, unless, while, until, etc.) may appear at the end of any statement. Some key words are optional (the ``then'' in an ``if'' statement for example). Parentheses may sometimes be elided in method calls. The receiver of a method may usually be elided. Many, many things are lifted directly from Perl. Built in regular expressions, $_ and friends, here documents, the single-quoted / double-quoted string distinction, $ and @ prefixes to distinguish different kinds of names (but with different semantic) and so forth. Like Perl, Ruby has very good text processing facilities. Like Smalltalk, everything in Ruby is an object, and Ruby has blocks, iterators, meta-classes, operator overloading, etc.
Ruby supports coroutines and exceptions out of the box like any modern language should. Among attractive Ruby features:
Ruby like Smalltalk, provides closures and code blocks and uses them in the same way. The Ruby collection classes and iterators are more powerful and elegant than similar Python constructs (lambdas and list comprehensions):
File.open(file, mode) do |f|
# do something with f (= file handle)
end
# f is closed automatically at this point
Look at this for example:
http://www.rubyquiz.com/quiz70.html
There are several useful documents about ruby written for Perl programmers. For example documentation To Ruby From Perl lists several differences:
$ and @ are used as the first character in
variable names sometimes, rather than indicating type,
they indicate scope ($ for globals, @
for object instance, and @@ for class attributes). def instead of sub. end keyword. foo.to_i,
foo.to_s, etc., if you need to convert between types. eq, ne, lt, gt,
ge, nor le. undef. In Ruby you have nil.
nil is an object (like anything else in Ruby). It’s not the same as an
undefined variable. It evaluates to false if you treat it like
a boolean. false and nil evaluate
to a false value. Everything else is true (including 0, 0.0,
and "0"). I would add that unlike Perl, Ruby has no variable declaration. This means there is no local variable scope. The first variable assignment defines its scope. There is no operators ++ and -- (may not yet :-). Also methods cannot be used before definition (one pass syntax analyzer).
Here is the list of gotchas from Ruby (programming language) - Wikipedia, the free encyclopedia
Gotchas and possible surprises
Although Ruby's design is guided by the principle of least surprise, naturally, some features differ from languages such as C or Perl:
- Names that begin with a capital letter are treated as constants, so local variables should begin with a lowercase letter.
- Boolean evaluation of non-boolean data is strict: 0,
""and[]are all evaluated to true. In C, the expression0 ? 1 : 0evaluates to 0 (i.e. false). In Ruby, however, it yields 1, as all numbers evaluate to true; onlynilandfalseevaluate to false. A corollary to this rule is that Ruby methods by convention — for example, regular-expression searches — return numbers, strings, lists, or other non-false values on success, butnilon failure (e.g., mismatch).- To denote floating point numbers, one must follow with a zero digit (
99.0) or an explicit conversion (99.to_f). It is insufficient to append a dot (99.) because numbers are susceptible to method syntax.- Lack of a character data type (compare to C, which provides type
charfor characters). This may cause surprises when slicing strings:"abc"[0]yields 97 (an integer, representing the ASCII code of the first character in the string); to obtain"a"use"abc"[0,1](a substring of length 1) or"abc"[0].chr.In addition, some issues with the language itself are commonly raised:
- In terms of speed, Ruby's performance is inferior to that of many compiled languages (as is any interpreted language) and other major scripting languages such as Python and Perl[4]. However, in future releases (current revision: 1.9), Ruby will be bytecode compiled to be executed on the YARV (Yet Another Ruby VM). Currently, Ruby's memory footprint for the same operations is better than Perl's and Python's.[4]
- Omission of parentheses around method arguments may lead to unexpected results if the methods take multiple parameters. Note that the Ruby developers have stated that omission of parentheses on multi-parameter methods may be disallowed in future Ruby versions. Much existing literature, however, encourages parenthesis omission for single-argument methods.
A good list of "gotchas" may be found in Hal Fulton's book The Ruby Way, pages 48-64. However, since the list in the book pertains to an older version of Ruby (version 1.6), some items have been fixed since the book's publication. For example,
retrynow works withwhile,untilandfor, as well as iterators.
See also Ruby for Perl programmers and Intro to Ruby for Perl programmers
Similarities
As with Perl, in Ruby,...
- Similar types:
- Strings
myStr = "This is a string"- Arrays
myArray = ['a','b',c,[d,e]]- Hashes
- hash = { myArray => 'first', 'b' => 'second' }
- NOTE: in Ruby any object can be a hash key
- Regex
myRegex = /^This/- Many special variables names. $_, $&, and the other ugly special variables.
- regexes are built right in. Ruby duplicates the syntax of Perl regexpes. However it also provides the OO syntax.
- there’s a fairly large number of commonly-used built-ins.
- parentheses are often optional
- strings work basically the same.
- there’s a general delimited string and regex quoting syntax similar to Perl’s (looks like
%q{this (single-quoted)}, or%Q{this (double-quotish)}, and%w{this for a single-quoted list of words}. You%Q|can|%Q(use)%Q^other^delimiters if you like).- you’ve got double-quotish variable interpolation, though it
"looks #{like} this"(and you can put any Ruby code you like inside that#{}).- shell command expansion uses `backticks`.
- embedded doc tools (Ruby’s is called rdoc).
- a package management system, somewhat like CPAN (though it’s called RubyGems)
Differences
Unlike Perl, in Ruby,...
- A constant is a variable whose name starts with an upper case letter.
- Role of semicolon
- Semicolon implisidly is presnt at the end of each line.
- Newline works as whitespace only when expression obviously continues to the next line.
- Otherwise newline finishes the expression, like semicolon.
- Many C++ style idioms like a << n1
- "What is truth?".
- Only false and nil are false
- That means that zero and empty string are true values!
- Methods can't be used before definition.
- Iterators are more powerful then map and grep
- used consistently in builtin libraries
- example: iterate through each member of an array:
array = ['a','b','c','d'] array.each {|item| puts item }- Making your own iterators: yield
def fibUpTo(max) i1,i2 = 1,1 while i1 <= max yield i1 i1,i2 = i2,i1+i2 end end fibUpTo(100) {|f| print f, " "} #prints: 1 1 2 3 5 8 13 21 34 55 89- you don’t have the context-dependent rules like with Perl.
- a variable isn’t the same as the object to which it refers. Instead, it’s always just a reference to an object.
- variables hold references to objects
- a=[1,2,3]; b=a; b[0]=0 #a->[0,2,3]
- So you need to use an object's 'clone' or 'dup' method to copy
- a=[1,2,3]; b=a.dup; b[0]=0 #a is unchanged, b->[0,2,3]
- although
$and @ are used as the first character in variable names, rather than indicating type, they indicate scope ($for globals, @ for object instance, and @@ for class attributes).- array literals go in brackets instead of parentheses.
- composing lists of other lists does not flatten them into one big list. Instead you get an array of arrays.
- it’s
definstead ofsub.- there’s no semicolons needed at the end of each line. Incidentally, you end things like function definitions, class definitions, and case statements with the
endkeyword.- objects are strongly typed. You’ll be manually calling
foo.to_i,foo.to_s, etc., if you need to convert between types.- there’s no
eq,ne,lt,gt,ge, norle.- there’s no diamond operator. You usually use IO.some_func instead.
- the fat comma is only used for hash literals.
- there’s no
undef. In Ruby you havenil.nilis an object (like anything else in Ruby). It’s not the same as an undefined variable. It evaluates tofalseif you treat it like a boolean.- when tested for truth, only
falseandnilevaluate to a false value. Everything else is true (including0,0.0, and"0").
A constant is a variable whose name starts with an upper case letter. In older Ruby implementations, when a constant was assigned a new value, a warning was issued. In newer Rubies, constants may not be reassigned from within instance methods, but can otherwise be changed at will.
Any Perl programmer who wants to start with Ruby should first get the Ruby source
distribution and read README.EXT. This is a good document, not only if you're writing
an extension library, but also if you want to understand Ruby more deeply. Next,
have a look at the source of the interpreter itself, and at the various supplied
extensions in the ext/ directory. You'll also find good examples under
contrib/ on the Ruby ftp sites.
|
About: Tiny Eclipse is distribution of Eclipse for development with dynamic languages for the Web, such as JSP, PHP, Ruby, TCL, and Web Services. It features a small download size, the ability to choose the features you want to install, and GUI installers for Win32 and Linux GTK x86.
October 27, 2005 (O'Reilly ONLamp Blog) In comments on Curt Hibbs’s What is Ruby on Rails?, he and Aaron Trevena, maintainer of Perl’s similar Maypole project have debated whether Ruby or Rails are doing anything particularly new.
For people who’ve only ever seen complex “enterprise-class” frameworks and libraries and designs as usable, certainly watching any of the Rails movies might give some evidence that being able to solve the 95% of all possible web programming problems that don’t need huge application servers and complex transactional and messaging systems with a fraction of the effort and perhaps fewer lines of code in general than the complex system requires lines of XML in configuration files is a good thing.
Of course, anyone using a decent set of libraries in Perl, Python, Ruby, or PHP probably already knew this.
Ruby does bring certain advantages; I much prefer the ActiveRecord syntax and introspection over that of Perl’s Class::DBI, but they’re both fantastically useful. They’re equivalent enough that neither offers an order-of-magnitude improvement over the other.
Where something like Python’s Django might invent and polish a new idea, the amount of time and work necessary to do something similar in Perl or Ruby isn’t large either. I don’t have enough practical experience with PHP 5 to judge there, but I’m sure it’s also flexible and dynamic enough to work.
In my mind, the issue isn’t “Ruby on Rails is more flexible and capable than standard J2EE or .NET for any project under a (very high) threshold of complexity”. The real point is that the simplicity, flexibility, and abstraction possibilities offered by dynamic languages and well-designed libraries — as well as a talent for exploiting radical simplicity, extracting commonalities from actual working code, and knowing when too much flexibility makes you less agile — offer a huge advantage over languages and libraries and frameworks and platforms that assume you need a lot of hand-holding to solve a really hard problem.
Yes, Ruby on Rails does what it does very well. It’s not the only thing that does, though. I wonder perhaps if some of the buzz and glow is that it’s new and shiny (in comparison), so that people haven’t already formed their own opinions about it, as they may have with Perl (oh, you can’t write readable and maintainable code), Python (all the fun of the Lisp community without half the things that make Lisp special), and PHP (a language that needs to grow up).
Fortunately, a lot of smart people already understand this. It would be nice to have the right debate, though.
Am I wrong? Is it really Ruby and Rails, or is it the dynamicism, flexibility, and better opportunitites for abstraction of dynamic languages that provide so much of the benefit?
Ruby user's guide:
http://www.rubyist.net/~slagell/ruby/
10 things every java programmer should know about ruby:
http://onestepback.org/articles/10things/
Coming to ruby from java:
http://fhwang.net/blog/40.html
Things I like:
-blocks
-you can be more expressive in ruby and essentially twist it into different domain-specific languages, see: http://blog.ianbicking.org/ruby-python-power.html
-I like how standalone functions essentially become protected extensions of the object class (like C# 3.0 extension methods):
http://www.rubyist.net/~slagell/ruby/accesscontrol.html
-using "end" instead of curly braces (easier for beginners and more readable)Things I don't like and never will:
-awkward syntax for some things like symbols and properties
-awful perlisms like $_,$$,$0,$1,?,<<,=begin
-80's style meaningless and over-abbreviated keywords and method names like "def", "to_s", "puts", etc.
-:: (double colon) vs . . (period).
Ruby is definitely better than python, but still not perfect, and still an order of magnitude slower than statically typed languages.
On the heels of last weekend's Ruby Conference in Denver (for a report, see Jack Woehr's blog), Sun Microsystems made a Ruby-related announcement of its own.
Led by Charles Nutter and Thomas Enebo, the chief maintainers of JRuby, a 100% pure Java implementation of the Ruby language, Sun has released JRuby 0.9.1. Among the features of this release are:
- Overall performance is 50-60% faster than JRuby 0.9.0
- New interpreter design
- Refactoring of Method dispatch, code evaluation, and block dispatch code
- Parser performance enhancement
- Rewriting of Enumerable and StringScanner in Java
- New syntax for including Java classes into Ruby
In related news, Ola Bini has been inducted into JRuby as a core developer during this development cycle.
Details are available at Thomas Enebo's blog and Ola Bini's blog.
Phil is talking about Ruby. Again, semi-realtime notes on Ruby.
Ruby is roughly 10 years old now. Matz liked Perl's text processing but didn't think that Python was OO enough. It's more of a Perl/SmallTalk blend. Classes, methods, objects, exceptions, message passing, iterators, closures, garbage collection, etc. And it's multi-platform, of course.
Back in 2000, Phil used a lot of Perl but found OO Perl tedious.
Why learn Ruby? It has a similar syntax but is different enough in some places to make you think differently. Strings, hashes, arrays, etc. Ruby can use any object as a key to a hash. Regexes, here-docs, etc.
@ means instance variable inside a class, not an array. The $ denotes global scope variable. @@ denotes a class variable. Semi-colons are optional at the end of line. Parens are optional in method calls.
False and nil are false. But 0 and '0' are true. Everything is an object.
Smaller community for Ruby, but that's okay.
Lots of interesting on-screen examples that I can't reproduce easily, so I'll just watch.
# Joe Grossberg said: 0 is true?!?This sensation in my head must be what those Python-haters feel when they unfairly dismiss a language with meaningful whitespace.
(I like Ruby to the small extent that I've played around with it. I use Python every day and I freaking love it.)
[1,2,1,3,5,7]-[1,3] -> [2,5,7]
['a','b','c']|['c','d','a'] -> ['a','b','c','d']
['a','b','a','c','b'].uniq -> ['a','b','c']
array = ['a','b','c','d']
array.each {|item| puts item }
def fibUpTo(max)
i1,i2 = 1,1
while i1 <= max
yield i1
i1,i2 = i2,i1+i2
end
end
fibUpTo(100) {|f| print f, " "}
#prints: 1 1 2 3 5 8 13 21 34 55 89
Bruce Tate's Beyond Java singles out Ruby as a top contender to displace Java. Tate, James Duncan Davidson, Robert Cooper and Bill Venners weigh in with their opinions on Ruby and its challenge to Java.
Short positive overview, explains Ruby by comparing with some other languages; focus on production; code samples, forum with many comments. -- Linux Journal
The Ruby Programming Language The Ruby Programming Language
Thirty-seven Reasons I Love Ruby
Programming Ruby - Second Edition
Do I really have to learn _another_ programming language :-), April 24, 2005
If you are like me, a busy programmer, I know you are wondering when you hear about Ruby, "Do I really have to learn yet another programming language?" I mean, Java, C#, Python? When will it ever end?
Reviewer: Randall Helzerman (campbell, ca) - See all my reviews
![]()
Well, it ends when you die, and yes, you do have to learn another programming language :-) But you'll like Ruby, I promise. Things I like about Ruby:
0. As easy to write scripts in as Perl, but it really scales.
1. Exceedingly self-consistent. Ruby has fewer syntactic warts than any programming language I'm familier with. All the features hang together very nicely.
2. Duck Typing: If you use a variable like a string, its a string. If you use it like a float, its a float. If you are familier with Haskell or or similarly typed languages, you get the idea. Ruby gives you about 80% of what Haskell gives you here.
3. Nice module system. This implements a nice mix-in facility--which gives you the power of C++ templates, with more structure. Also eliminates the need for multiple inheritance.
4. Wacky features like call/cc for the true language freaks.
Oh, so you want to know about the book too? Well, I agree with some of the reviewers here who describe the book as less of a tutorial/visionary screed/inspiring gospel and more of a reference manual. But I don't think this is a fair critique of the book. Back in the 60's, before the internet, a language needed a book to do for it what K&R did for C, or what Clocksin & Mellish did for prolog.
But today, you learn about a language by surfing the web. Instead of just duplicating what is available on the internet, this book complements the web, by supplying in a nice portable package what you need to know about Ruby which _can't_ be (easily) gotten from the web. Its a "post-internet" volume in this fashion.
Really the only critique of the book I can offer is that its description of Ruby/TK, the default GUI programming library for Ruby, is a bit abbreviated. It gives you the basics and the refers you a book about Perl/TK for the details. Please guys, in the next edition expand on this!
Ruby is a language which is as object-oriented as SmallTalk, as flexible as Scheme, has the scriptibility of Perl, and a nice C-ish syntax. What's not to like? This book is the book to buy if you decide to learn Ruby.
Ruby and the Rails framework (Ruby on Rails) have gotten major attention in the past year, primarily as an alternative to the complexities of using Java and J2EE APIs for typical N-tiered web applications using a Model / View / Controller framework.
Reviewer: stlreader "stlreader" (St. Louis, MO USA) - See all my reviews
"Programming Ruby" is supposed to be a combination of primer and reference for the Ruby language. Compared to some of the "classics" in programming such as "Programming PERL" (Larry Wall), "The C Programming Language" (Kernigan & Ritchie) or "The C++ Programming Languate" (Stroustrup), this book falls way short as both a primer or reference.
First of all, if you're interested in Ruby at this point, you're probably interested in using the Rails framework built using Ruby. This book provides NO information about Rails at all. This isn't a fault of this book, it's just something you need to know because many code examples you'll find on the web aren't "Ruby" examples per se, they are examples of using APIs within the Rails framework. Another book by this author is due out shortly covering Rails but based on the organization of this book, I would browse it in a bookstore before buying.
I've learned multiple programming langues over the years (Pascal, C, C++, a bit of Assembler, UNIX shell, PERL, Java) and I think most programmers expect any book on a programming language to tackle the material in the following order:
* installing the language
* running or compiling a basic program
* data types for the language
* variables, assignment and data structures / objects
* conditional expressions / control structures
* unit / module organization for source code
* advanced class / object concepts
* standard libraries for DB, network, security functions, etc.
As another reviewer stated, this book doesn't explain the Ruby language's use of symbols (:somesymbol) until page 323, even though it would be logical to explain symbols at the same time Ruby's hash type is explained. The difference between this variable, @thisvariable and @@thisvariable is explained very early but seems out of context because the scope of these variable types isn't clarified until the reference section. I think most experienced programmers will find the sequencing of chapters in this book confusing.
You can definitely learn key aspects of Ruby from this book but this will definitely not be the only book you'll want or need if you are learning Ruby to use Rails. Rails itself definitely shows some promise for simplifying some aspects of web development but I presume it will take another 2 years or so for the framework to stabilize and useful documentation to emerge. It definitely isn't clear from this book how Ruby as an underlying language for the Rails framework was a better or needed choice over implementing something like Rails with PHP or PERL that have already achieved wide familiarity.
Reviewer: calvinnme "Texan refugee" (Fredericksburg, Va) - See all my reviews
![]()
This book is an excellent one on learning the Ruby language if you already know object-oriented programming and are coming from the C++ or Java world in particular, since the authors often compare how you do something in Ruby to those two languages. If you don't already know object orientation I think you'll be lost. This is a book not only about the Ruby language and its syntax, but Ruby and its environment. There is an entire chapter entitled "When Trouble Strikes" that talks about the ruby debugger, interactive Ruby, profiling to look for code bottlenecks, and a common list of mistakes that Ruby programmers make. In "Ruby and the Web" the book shows how easy it is to write HTML forms using Ruby, and in a reverse move, how easy it is to embed Ruby in HTML by using eRuby. In "Extending Ruby" it is shown how Ruby itself can easily be extended by writing extensions in the C programming language.
This book also helped me compare Java and Ruby as languages to the point that I can now see the various advantages that Ruby has over Java. For example, built-in lists/arrays and hashes/dictionaries in Ruby are a big win over Java and its library-based collections. Java 5.0 fixes some of this but, in Java, collections still seem tacked on rather than integrated as in Ruby. Another big win of Ruby over Java is its ability for dynamic code loading. You can do it in Java but again, it seems tacked on. Also, Ruby object-oriented completeness over Java's dichotomy between primitive types vs. objects is a big plus for Ruby.If I have any criticism of this book, it is that although complete, the chapters seem somewhat out of order. In particular quite a bit of the material in part 3, "Ruby Crystallized", seemed to only be repeating material in part one. However, it is still the best book out there for getting a detailed look at the language and its environment. I notice that Amazon does not show the table of contents for this book, so I do that here:
PART 1- FACETS OF RUBY
1. Getting Started
2. Ruby.New
3. Classes, Objects, and Variables
4. Containers, Blocks, and Iterators
5. Standard Types
6. More About Methods
7. Expressions
8. Exceptions, Catch, and Throw
9. Modules
10. Basic Input and Output
11. Threads and Processes
12. Unit Testing
13. When Trouble Strikes
PART 2 - RUBY IN ITS SETTING
14. Ruby and Its World
15. Interactive Ruby Shell
16. Documenting Ruby
17. Package Management with RubyGems
18. Ruby and the Web
19. Ruby Tk
20. Ruby and Microsoft Windows
21. Extending Ruby
PART 3 - RUBY CRYSTALLIZED
22. The Ruby Language
23. Duck Typing
24. Classes and Objects
25. Locking Ruby in the Safe
26. Reflection, ObjectSpace, and Distributed Ruby
PART 4 - RUBY LIBRARY REFERENCE
27. Built-In Classes and References
28. Standard Library
APPENDICES
A. Socket Library
B. MKMF Library
C. Support
D. Bibliography
The Ruby Programming Language The Ruby Programming Language
Delightful Languages: Ruby - Medium length positive review, with code samples, references; PDF format. [The Perl Review] (November 1, 2002)
Copyright © 1996-2008 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. Submit comments This document is an industrial compilation designed and created exclusively for educational use and is placed under the copyright of the Open Content License(OPL). Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.
Standard disclaimer: The statements, views and opinions presented on this web page are those of the author and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.
Last updated: June 02, 2008