Ruby Language

Ruby is a DynamicallyTyped, ObjectOriented ScriptingLanguage, which is very popular in Japan. Until recently, it was only moderately popular in the West, but RubyOnRails seems to be changing that. Its closest cousins are PythonLanguage, PerlLanguage and SmalltalkLanguage ('Ruby' is a play on 'Perl'). Ruby-lovers claim it has incredible OO expressiveness and more flexibility than Python. Python-lovers claim Python is better-supported and more mature. They may both be right.

Useful pages:
Hello world in Ruby:'
 print "Hello World!\n"
or, using the more common Ruby idiom:
 puts "Hello World!"
or, for CeePlusPlus fans:
 $stdout << "Hello World!\n"
or, for CeeLanguage fans:
 printf("Hello World!\n")
or, for those who like their output raw:
 p "Hello World!"

Articles: [1] This article is fairly old now, and many of the complaints it has about Python no longer apply.

HelpMe: I need a reliable language which lives in ordinary files and has good up-to-date libraries and (most importantly) good up-to-date web frameworks. Obviously RubyLanguage is the way to go. But having used IoLanguage a lot, and also played with SmalltalkLanguage, LispLanguage and IokeLanguage, RubyLanguage just seems BORING. Can anyone help me get really excited about it please? -- JasonGrossman


Praise for Ruby:


For me, Ruby is the successful combination of SmallTalk's conceptual elegance, Python's ease of use and learning, and Perl's pragmatism.


I like it too! It has some kind of elegance, like EiffelLanguage, but it has a Perlish flavor nevertheless... I've found the developers and those on ruby-talk pretty supportive and friendly and considering the lots of programs I've found in archives with the README in Japanese, I'd pretty much accept it has more users than Python (after all, there aren't that many Python users...)

One thing I absolutely love: Procs (i.e. code blocks). I knew about them (or similar) in Lisp and Smalltalk, although didn't recognize them until I met them on Clipper 5(.1?). Found them really cool. I was learning C++ by then and found them really missed. Then I've found them in Smalltalk and in BrainLanguage, which it's somehow pretty cool as well... look at http://brain.sourceforge.net.) -- DavidSdeLis?


When you consider the depth of its OO support, Ruby is close to Smalltalk - far closer than (say) Python. In Ruby, everything is an executable statement, and many of these are simply method calls. For example, to declare a class with a (read-only) attribute, you could write:

	class Example
	  attr :fred
	end
The 'attr' line looks like syntax, but is actually just a method call into the Class object (yup, it has metaclasses). If you want to, you could redefine 'attr' (for example, to change the default accessibility, or to trace all reads or writes to the variable, or perhaps to implement some kind of lazy persistence). Add to this depth facilities such as iterators, closures, mixins, and a clean syntax, and you end up with a language that's practical for writing large scripts, but also fun to play with.


I like Ruby very much from having played with it a short time. It seems to combine most of the things I like most about Perl, Python, and Smalltalk (except for the use of words rather than braces to for program structure, yuck (except in the case of blocks)). The Python philosophy is a little too much "There's only one way to do it" for my taste. Ruby combines the cleanliness of Python with the flexibility and concision of Perl and the pure object-orientedness of Smalltalk. The English book [ProgrammingRuby] is now out, and it's excellent. Even better, the complete text is available on the Web at http://www.rubycentral.com/book/index.html. -- DanSchmidt

:you can always use braces instead of keywords. --ShawnL

I've written scripts in Perl, Python, and Ruby. I like Ruby best by far. Now if I can get my ISP to put it up on my web site without killing me (after I pushed him for Perl and Python) ... -- RonJeffries


Hedging about Ruby:


Maybe I am just not willing to get too bleeding edge, but after looking at the Ruby site (URL at top of this page), I chose not to spend time learning Ruby at this time. I have been experimenting with Python, and have used it for some text manipulation projects with great success. One example is parsing an SNMP MIB and creating a header file with the corresponding MIB variables in it. That way, as Marketing changes the MIB around, I just run a script to recreate the header file. I only have to change my Cpp code if they add or remove variables. Perl seems much more widely used than Python, but Python's readability convinced me to use it. Ruby may be a better language than Python or Perl, but too few people are using it, and the documentation is still too obviously translated from Japanese for me to feel comfortable using it. -- AnonymousDonor Six months later... Now with the PickAxeBook and great online resources (like the PoignantGuideToRuby), I am learning Ruby for use as my default utility language.


I'll preface this by stating that I actually love Ruby. It's a great scripting language for my needs, and I've been using it quite a bit... enough that I start running into the warty, awkward bits that plague any language. My two "favourites":

  $ ruby script.rb
  script.rb:<last line of file>: syntax error
I swear to God, Ruby has the worst diagnostics of any program I've ever used except ed. It's like the old joke about "KenThompson's automobile"... 90% of the time, it won't say anything more useful than "syntax error", and usually it can't even give you the correct line number to start looking at. Oy gevalt!

Phew, that was cathartic.

I've noticed the syntax error at end of file syndrome as well. It usually seems to mean that you started a construct but missed it's corresponding end. I've been reduced to commenting out swathes of code (say, an entire class) in an attempt to track this kind of thing down. Let's say it's an area of the parser which could be improved. And while I'm on the subject, a couple of my pet peeves:

  10.times
  {
	|i|
	puts i
  }



Speaking of refactoring - where is the RefactoringBrowser for Ruby? I've recently been getting into learning it, but I realized how spoiled I was with the EclipseIde's support for Java refactorings. -- StevenNewton

''A RefactoringBrowser for Ruby is here: http://www.kmc.gr.jp/proj/rrb/index-en.html. It works with EmacsEditor and FreeRIDE) -- pate


Software implemented in Ruby:


TestingFrameworks



Request for SUCCESS real file stories for ruby.... waiting for the miracle... profit... challenge... success... -- AndreySidorenko

See http://wiki.rubygarden.org/Ruby/page/show/RealWorldRuby.

One area where Ruby really shines is in creating domain specific languages. Turns out that Ruby's blocks make this easy to do. I created a Hardware Description Language/simulation environment using Ruby (RHDL) that ended up looking very much like an existing HDL (VHDL). No parser was needed - it's all pure Ruby. This would have been very difficult to do in Python since Python doesn't seem to have anything equivalent to Ruby's blocks. BTW: I was able to implement the first version of RHDL in about 300 lines of Ruby. In addition to Ruby's blocks, the fact that Ruby has continuations also helped a lot. -- PhilTomson?


While Ruby is nice, I can't help but think that the designer has a bit too much of the "OOP is the light and the way" philosophy in him, a philosophy that I thought represented many of the programming failures of the 1990s. Was the trouble with Perl really that it needed pervasive OOP-ness? That's up for debate.

What failures would that be, to be more specific? Even though Ruby has taken some ideas from Perl, I think it is a mistake to view it as "Perl with OO", as you seem to imply. -- AndersBengtsson

To be fair, Matz's view is not as dogmatic as you make it out. To quote from a Usenet posting (7/24/2001):
	"It's easy for my mind. I hope it's easy for yours too." -- matz
I.e. he just likes OO programming, so he wanted a language that would let him do it easily. -- StevenGrady

What programming failures of the 1990s are attributable to OOP, rather than organizational issues?

Ruby is not dogmatic about ObjectOrientedProgramming. You can write programs that range from a sequence of statements, through a ProceduralProgramming style, to classes/modules/objects as takes your fancy. It just happens that the first two styles are implemented in terms of the third, but as a programmer you can ignore the extra complexity if you don't want it. Ruby is therefore a very scalable language and you can pick the appropriate style for each problem.

But Ruby has less support for a FunctionalProgramming style than e.g. Python (functions as first class objects, ListComprehensions, ...) has.

It looks to me like Ruby has much more support for functional programming than Python, simply because Python doesn't have true closures and lambdas can only be one expression. Ruby has nice Smalltalk-ish blocks (BlocksInSmalltalk?), and a lot of standard functions that like to take blocks as arguments.

Closures were added to Python recently. Unfortunately, BlocksInRuby can't be used in exactly the same way as functions.

Strictly speaking, Ruby doesn't have stand-alone functions. But it does have objects, and you can use blocks in exactly the same way as objects. In practice, this hasn't been shown to be a problem.

Neither Ruby nor Python are functional languages. But both have features that are reminiscent of a functional style.

An additional note about why Ruby was created. It wasn't because Perl is not OO enough. It was because there was no good scripting language that could handle Japanese text. While Matz was creating Ruby, he gave it the OO model he liked, reduced most of what makes Perl effective down to a class library (and stole syntactic sugar) and added in anything else he liked. But Japanese support was what he needed.

As for not having stand-alone functions, try passing a block into Proc.new and the object that you get back is close enough for any use that I can think of. -- BenTilly

YukihiroMatsumoto follows a RuleofNonOrthogonality? in his LanguageDesign, so that he won't add features to a language that are orthogonal. My guess is that he considered BlocksInRuby and ListComprehensions to be orthogonal.

I think you are mistaking orthogonality for equivalence or interchangeability.


I like a language where I don't need to read the tutorial. I just guess based on what I liked about legacy languages. For example, you return a value with a 'return' statement. You don't return by assigning a value to the current function's name. -- PhlIp

Oh, yeah. And = assigns, while == compares. Duh!

One day I'd like to see a language that uses := for assignment, == for comparison, and leaves = as a syntax error. EeLanguage.

See AssignmentVsEqualityOperator, BondageAndDisciplineLanguage. Subcategory: The kind that makes you type two characters instead of one for the most common operator, on principle. Why not? ConservationOfKeystrokes is IMHO one of the worst design principles for a programming language; especially if the difference is one keystroke. := is two keystrokes more than = (shift + ;/:).

Ruby in general is a very fluid language, and if you're the sort of programmer who depends on the interpreter or compiler to correct your mistakes, then Ruby is not the language for you. Everybody's style is different. Personally, my own experience has been that working in more rigid language doesn't do a thing to prevent me from making mistakes - there are many bugs that the interpreter or compiler can't catch. Ruby doesn't prevent me from making those mistakes. But it does save me lots of time - time which I then use to write lots of UnitTests, which do prevent me from making mistakes. -- francis

How about : for assignment and = for comparison, like the SelfLanguage? That's one character for each, and I never ever mix them up.

How about making variables objects. And assignment is the default message you send to the variable object (not the underlying reference). anintvar 5, now the variable "anintvar" is a reference to the constant integer 5. And since variables are objects, you can do some neat things like subclass variables. It would be a mixed world of static variable typing and dynamic. Use the appropriate one for a given scenario. You could also do linear casting. exm.
			integer new anintvar 5
			char new acharvar anintvar
Variable types and the reference object they point to can be 2 different types. But the variable decides how to do the casting not the object referenced. "anintvar" and "acharvar" reference the same object.


Ruby variable names are preceded by 0-2 at-signs depending on how long they stick around. A method variable would be called "lastWord", an instance variable "@lastWord", and a class variable "@@lastWord". I don't know if Matz intended it it this way, but this makes it easier to see dependencies at a glance.

Let's say you have some a method that you want to move to another class:

 class OriginalClass
	def linkToOneWord(wordsSoFar, nextWord)
		prevWordIndex = wordsSoFar.size - 1
		prevWord = wordsSoFar[prevWordIndex]
		rank = @wordRanker.rank(prevWord)
		prevWords = wordsSoFar[prevWordIndex - rank + 1, rank + 1]
		while prevWords.length > 0
			wordPicker = @wordPickers[prevWords]
			wordPicker.add(nextWord)
			prevWords = prevWords[1 .. prevWords.size-1]
		end
	end
 end # OriginalClass
Look for the at-signs, and you know where you're coupled. Immediately the language points out two good places for this method to be moved: the classes of either @wordRanker or @wordPickers.

In addition, I know that if I move the method to the class of @wordPickers -- let's say it's called WordPickerCollection, then I need a line of code in OriginalClass.linkToOneWord to give WordPickerCollection.linkToOneWord the value in @wordRanker.rank(prevWord).

My new code might look like:

 class OriginalClass
	def linkToOneWord(wordsSoFar, nextWord)
		rank = @wordRanker.rank(prevWord)
		@wordPickers.linkToOneWord(wordsSoFar, nextWord, rank)
	end
 end # OriginalClass

class WordPickerCollection def linkToOneWord(wordsSoFar, nextWord, rank) prevWordIndex = wordsSoFar.size - 1 prevWord = wordsSoFar[prevWordIndex] prevWords = wordsSoFar[prevWordIndex - rank + 1, rank + 1] while prevWords.length > 0 wordPicker = self[prevWords] wordPicker.add(nextWord) prevWords = prevWords[1 .. prevWords.size-1] end end end
I wonder if ruby-mode in Emacs can be set up to change the colors of single and double at-signs. (If I actually knew how to do all the stuff you can do with Emacs, I might implement such a thing myself.) -- francis

Have a look at http://relativity.yi.org/el/code-keywords.el. (BrokenLink 2005-05-01) It colours words like TODO and FIXME. You may be able to modify it to colour single and double at-signs. -- ChanningWalton


Ruby requires a lot less typing than many other languages. Commands don't need to terminate with a semicolon; they simply end at endline. (Or the continue to the nextline if you implicitly state that the command's not over, using e.g. a trailing "+", or explicitly using a trailing "\".) Variable names aren't preceded with a $, and function arguments don't always need to be grouped with parentheses.

Isn't it easier to make a dumb syntactical mistake, without those restrictions?

Sure it is, but you get used to the quirks soon enough. And besides, are syntactical mistakes really what eat up most of your programming time?

On the contrary, I'd say it makes it less easy to make a syntactical mistake, since there's less syntax to make the mistake in.

That's why the BrainfuckLanguage is the easiest to use of them all.


And it [Ruby] is nice. Last week:

1. I had to brush up on my Perl (just to read someone else's code), and was reminded of its power.

2. For the second time in my life, got Python, read the introduction document, and played a bit with it.

2a. As was the case when I first went to see what all the Python talk was about, decided that the language was not nearly as powerful as Perl, much less elegant than JayLanguage, and not really object-oriented at all. (Struck me as something of an afterthought.)

Could you expound on that last assertion? As I see it, treating things like Classes and Functions as objects (as PythonLanguage does) is going above and beyond the requirements of an OO language. (I should have brought my HolyWarUmbrella?, I'm feeling a shift in the wind.) -- IsaacFreeman

3. Downloaded the Windows executable for Ruby, skimmed the documentation, and looked at and ran some demo scripts. I think I like it! I don't know if I agree it is a good Perl replacement (but it tries -- the author says he was inspired by Larry Wall's work and approach), but the language itself strikes me as a nice improvement over Python. (The claim is made that in Japan, more folks are using Ruby than Python already.) -- JimRussell


As a long time Perl user, I love the power of Perl, but have been dissatisfied with the cryptic nature of Perl code. In particular, using objects in Perl is painful. I've been meaning to make the move to Python just to get better OO support, but I was finding it difficult to translate my Perl based knowledge into Python. I discovered Ruby this past summer and found it easy to make the switch from Perl to Ruby. All the power of Perl, with a clean syntax and an OO system that is very reminiscent of Smalltalk. I highly recommend looking into Ruby. -- JimWeirich


In a bake-off between Java, Python and Ruby for my new Web site project, we selected Ruby and I'm very happy. I love the language syntax - it is short and readable at the same time, matches my intuitive thinking mode even better than Smalltalk (I evaluate a language on that and shortnes of typing [millimemes/keystroke is the unit of measure, but it has to stay readable]. ... That having been said, I detest the @ and @@ variable names as they really clutter up the eye and make the rest of the code harder to read, and the absence of a development environment is <unspeakable>. Programming back in the 1980s, (shudder). ... So you might take it as strong evidence of the niceness of the language that we are using it anyway. -- AlistairCockburn (See TheProblemWithSigils about @ and @@)


In summary, this language makes you feel loved. (In remarkable contrast to some other languages.) -- PhlIp


I personally like to use Ruby too but I've found some quirks that bother me slightly. A few weeks back I was deciding whether to use python or ruby and I read both tutorials. In the end (after a long self-debate) I chose for Ruby as it's cleaner, though it lacks the richness in libraries of Python.

Recently, however, I've noticed the quirk I was mentioning: when you access an instance-variable with an attr_reader you can modify it. I though the principle of an attr_reader was a getter. But if I do something like:

 class SomeClass
	attr_reader :myvar
 end
...
  myClass = SomeClass.new
  somevar = myclass.myvar
  somevar.changeFunc	=> results in a change in the original myvar too.
Now I know that Ruby uses pass-reference-by-value (Like Java) but still, I'd expect an attr_reader to give a clone of the instance-variable, or ensure the object is not changeable. Attr_readers may be useful for quick-typing, but they quickly lose their use as you can't add code to them, thus disabling you from freezing objects and cloning objects, etc...

Just my 2 cents -- ChristophePoucet?

P.S: I still use Ruby happily


The above is trivially solvable using meta-programming, which quickly becomes a habit in Ruby - or at least did for me. If I saw the need to have this kind of attribute easily available, I'd do something like:

 # If you want this to be generically available (in ALL classes), replace "SomeClass" with "Class"
 # in the next line.
 class SomeClass
	def self.attr_clone(*args)
		args.each { |arg|
			module_eval "def #{arg}() @#{arg}.clone end"
		}
	end
 end

# Later use this to define a variable accessor: class SomeClass attr_clone :myvar end
This really helps cut down on code size in a lot of cases - to take a recent instance, field accessors for fixed width fields in a text file was something I defined by creating a small MetaMethod? like above, and then just pasting in column numbers from the spec (and optionally a conversion method to apply to the String object generated - e.g., :to_i).

-- EivindEklund


Maybe Ruby is just an inferior Smalltalk? Seems that when I ask Ruby programmers, at least for old-timers, why they like Ruby, the answer is usually "It's the closest thing to smalltalk". Usually you'd hope for "it's like Smalltalk but better", as in the frequently heard comment in the late 1990s "Java is like C++ but better". Are former Smalltalkers adopting Ruby with genuine enthusiasm or reluctant realism? -- AnonymousDonor

Ruby's got a few nice language features that I miss in Smalltalk, but the reverse is also true. I like both languages; it's the environment that I miss when I work in Ruby. Emacs is wonderful, but it doesn't understand my objects the way Smalltalk does. -- AdamSpitz (not an old-timer)

I have used both Ruby and Squeak (SmalltalkLanguage implementation) and I must say that while Ruby is more useful for getting stuff done (more pragmatic), there is much more interesting stuff in Squeak. The whole environment understands objects, the browser is absolutely fantastic, etc. I think if there was a Squeak-like environment for Ruby (or if Squeak was made to understand Smalltalk-80 AND Ruby) then I think that modern programming a la Squeak could get more exposure. I also gotta say that though Ruby is pure OO, Smalltalk is even more. I like that ifTrue:, ifFalse: and ifTrue:ifFalse: are methods of the boolean class.

"Java is like C++ but better". - funny, I've always said that "Java is like C++, but with the interesting stuff taken out". -- RogerLipscombe

Ruby's lack of a monolithic graphical IDE will be viewed by some as a feature, not a bug.


One thing I don't see people complaining about: the ugly Perlisms in Ruby. Though I quite like Ruby, I felt since the beginning that there's a core language in it that needs to be extracted, and a lot of fluff that needs to be thrown out. The latter is primarily, in my opinion, all of the $-initial variables (especially $_, aaargh), and the statement modifiers:

:try require "English" http://www.ruby-doc.org/stdlib/libdoc/English/rdoc/index.html --ShawnLandden?

  puts "Hello world" if false
I really, really think the test belongs first, and the statements whose execution depends on the test need to be indented.

Here is some nasty code that IIRC Ruby allows:

  if 2 > 1
	puts "Hello world"
  end unless 5 > 2
The if statement never gets evaluated, IIRC.

It's there to allow readability and make the language more English-like. There are many features of many languages that could be misused, but that doesn't make them bad.

  process unless broken
or

  if not broken
	process
  end
It's not much, but it can really help in the right situation.

(But does it really improve readability? It puts the condition after the conditionally executed code, and doesn't indent the latter. Doesn't a regular if statement mirror the meaning of the close more closely, plus draw more attention to the fact that there's a branch at this statement? And, does "readable code" really mean "more English-like code"?)

Readability is probably a subjective thing that varies from person to person. I'll say in my case that sometimes I find the one line "do_something if condition" much more readable than the more traditional "if condition; do_something; end" construction. You might not. That's okay.

People who don't use Ruby extensively sometimes lump it together with Perl, since its flexibility allows you to write lousy code. It's true that you can write lousy code in Ruby, but you certainly don't have to. The problem with Perl is not that it allows you to write lousy code, but that it doesn't offer you enough easy ways out of writing lousy code. Ruby does. -- francis


"Come to think of it, does Ruby have higher order functions?"

Yes, a HigherOrderFunction, by definition, is a function that acts on or returns a function. Therefore, in Ruby, any function that can take a callable object (block, method, or any object with the "call" method) is a HigherOrderFunction. All the examples given in this page are HigherOrderFunctions.

Ruby has a convention for higher order function emulation, yes. Sadly, it's not unified with the block mechanism, which aims at partly the same solutions. BTW: Can you write anonymous "functions" like these (objects with a call method) in Ruby? (Answer: Yes) And less related, can an iterator (or whatever a method receiving a block is called) pass the block to a subroutine? (Answer: Yes)


More than most OO language coders, Rubyists tend to believe in the PowerOfPlainText, using neat-o formats like YamlAintMarkupLanguage, TextileFormat, Wiki and Ruby's own native RdocFormat. While tools for all of these (except RDoc) existed in other languages first, Ruby's small developer base has allowed a very nice ecosystem to grow up around them. This seems to be becoming an integral part of the RubyWay; as far as I know Ruby 1.8 is the only language out there with YAML support in the core library distribution.

Indeed, it's the PowerOfPlainText and the ability to use Ruby as PowerTool in tandem with other tools that make it more palatable to many than Smalltalk.
See InspectEvalFileFormat, BlocksInRuby

Bow before RubyForge.

Evangelize in PythonVsRuby and RubyVsPerl

Discussion in RubyInsteadOfSmalltalk
Ruby is an AgileLanguage
Links from Ruby to code in other languages


RubyGui

There are several ways to form a Ruby GUI.
Interprocess Communication using Ruby


Logging from Ruby


Embed Ruby in a web page


Ruby Books


Ruby Patterns


CategoryProgrammingLanguage CategoryRuby CategoryScripting

EditText of this page (last edited July 26, 2009)
FindPage by searching (or browse LikePages or take a VisualTour)