Published on

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. #30Get More Refcardz! Visit CONTENTS INCLUDE: Essential Ruby n Ruby Language Overview n Simple Ruby Examples n IRB n RubyGems n Ruby Language Reference Tables By Melchior Brislinger and Peter Cooper n Hot Tips and More... AbOUT RUby SImpLE RUby ExAmpLES Ruby is an easy-to-learn, dynamic, object-oriented programming Despite being an object-oriented language, it is not necessary language with dynamic typing and automatic memory to use explicitly object-oriented syntax within a basic Ruby management. While object-oriented at heart, it provides program. While everything works on objects (and methods facilities for procedural and functional programming as well as called upon those objects) behind the scenes, you can write extensive support for introspection and meta-programming. a program as simply as this: Ruby’s core API, extensive standard library, and thousands of def fib(i) if high-quality external libraries make it suitable for many different 0 programming tasks in multiple disciplines (key examples being elsif i == 1 network programming, Web applications, shell scripts, data 1 else processing, and text manipulation). fib(i - 2) + fib(i - 1) Ruby is already installed on Mac OS X and many Linux end end distributions. For Windows the easiest way to install everything necessary is the Ruby Installer ( puts fib(10) This refcard provides a quick reference to language elements This script prints to screen the 10th number in the Fibonacci sequence. It defines a method called fib that returns the and many important API functions for quick lookup. relevant result from a simple if/elsif/else expression. Note the use of standard equality syntax (==), addition (+), subtraction RUby LANgUAgE OvERvIEw (-), and method calling (fib(10)), but also note the possibility of using methods in somewhat idiomatic ways ( rather Ruby is considered to be a “pure” object-oriented language than i == 0—though the latter would also work). The use of because almost every concept within Ruby is object-oriented demonstrates calling a method upon an object (where in some sense. Yukihiro “Matz“ Matsumoto, Ruby’s creator, i is the object, and zero? is the method). wanted to develop a language that operated on the “principle of least surprise” meaning that code should behave in a non- confusing manner and be reasonably self-explanatory (beyond Hot The main Ruby interpreter is usually invoked by Tip running “ruby” from the command line. If it is the basic syntax). Matz also wanted Ruby to be a pleasurable given a filename as an argument that file will be language with which to program, and not make unnecessary run (e.g. ruby myscript.rb). The interpreter has several demands upon the programmer. other options that are listed in the “Ruby Interpreter Argu- Ruby is considered a “reflective” language because it’s possible ments” table in this card’s reference section. for a Ruby program to analyze itself (in terms of its make-up), make adjustments to the way it works, and even overwrite its own code with other code. It’s also considered to be “dynamically typed” because you don’t need to specify what Get More Refcardz type of objects can be associated with certain variables. Objects (They’re free!) are considered prime in Ruby and whether you’re passing n Authoritative content around a string, a number, a regular expression, or even a class, Designed for developers Essential Ruby n you’re just dealing with an object from Ruby’s point of view. n Written by top experts Ruby will seem reasonably familiar to Python and Perl n Latest tools & technologies programmers (and to a lesser extent C# and JavaScript n Hot tips & examples n Bonus content online developers) as Ruby was heavily inspired by Perl in certain areas n New issue every 1-2 weeks (as was Python). Ruby is less similar to languages like C, C++ or Java because these languages are compiled (not interpreted), Subscribe Now for FREE! statically typed, and focused on performance rather than flexibility and conciseness. DZone, Inc. |
  2. 2. 2 Essential Ruby tech facts at your fingertips Simple Ruby Examples, continued IRb Developing a program with “true” object-oriented syntax is not significantly different. For example: IRB (short for “Interactive Ruby”) is an interactive prompt or class Person “Read-Eval-Print-Loop“ (REPL) that uses the Ruby interpreter. attr_accessor :name, :age Anything you type is evaluated by Ruby and the response printed to screen. IRB can be invoked by running “irb“ from the def full_info return "#{@name} is #{@age} years old" command. A demonstrative session shows the usage: end irb(main):001:0> 3 + 5 end => 8 fred = irb(main):002:0> "hello there " * 3 = "Fred" => "hello there hello there hello there " fred.age = 45 puts fred.full_info irb(main):001:0> "A String".class => String In this example, a class (Person) is defined, and attributes (name irb(main):002:0> "A String".methods.sort and age) and a method (full_info) are defined upon that class. => ["%", "*", "+", "<", "<<", "<=", "<=>", "==", Below the class definition, we then create an instance of the "===", "=~", ">", ">=", "[]", "[]=", "__id__", "__ Person class and assign it to a variable, fred, before assigning send__", "all?", … values to its attributes, and then calling that instance’s full_info irb(main):003:0> "A String".class.methods.sort method (which, in turn, uses instance variables—prefixed with @— => ["<", "<=", "<=>", "==", "===", "=~", ">", ">=", to create its output). "__id__", "__send__", "allocate", "ancestors", "autoload", ... IRB is most commonly used when learning the Ruby Hot “This is a test” is a string with no special qualities programming language, and also as a handy “sand box” to try Tip (and, remember, it’s also an object in Ruby) out new programming tricks and techniques quickly. IRB can be but it’s possible to interpolate data into it (from used to interactively explore classes, test pieces of code and variables, etc.) with a special syntax: is also used as a console to inspect and manipulate running programs, for example, in Web applications. "2 plus 2 is #{2 + 2}" The #{} construction serves to interpolate the result of the Want to try Ruby without installing anything? expression within the curly braces—in this case 2 + 2 is Hot Tip Or want to get a walkthrough tutorial? Go to calculated to equal 4 and so the string ends up as "2 plus 2 is 4" It’s a Web-based version of IRB and Ruby, and features a tutorial to bring you up to speed. Earlier we called Ruby a “reflective” language because it offers functionality to programs to change, extend, and otherwise inspect themselves. We can look at a key Ruby idiom and RUbygEmS reflective feature—class reopening—by changing the Fibonacci example from earlier to the following: RubyGems is the official Ruby package manager (though, notably, it is not included with default Ruby 1.8 releases by default— class Integer although it is present within Ruby 1.9 and on the OS X version def fib if of Ruby 1.8). It allows developers and users to easily search, 0 install and update Ruby libraries and their dependencies and elsif self == 1 works in a similar fashion to other package management tools 1 (such as yum and apt-get). else (self - 2).fib + (self - 1).fib Gems are installed by running “gem install“ and the name of end the gem (e.g. gem install rails). Running “gem update“ updates end all installed gems to their latest official versions. end A selection of popular Ruby gems/libraries: puts 10.fib gem/library Description URL Note this time that in order to get the Fibonacci number, we’re Rails The famous Web application framework no longer calling a global fib method, but a method that works Rake A Ruby based build system (like a Ruby equivalent of make) directly upon the number 10 itself (remember, everything is an Capistrano A tool for automatic remote object—even the number 10!). The way this is achieved is by deployment tasks “reopening” a standard Ruby class—Integer—and defining Mongrel A Ruby Web server and HTTP daemon library a new method called fib within it. This then makes the fib rspec A “Behavior Driven Development” method available to all objects of class Integer in Ruby! Note (BDD) framework that the content of the integer object itself (the number we camping A tiny web framework camping need to use) is obtained with the self keyword. self, in this case, returns a representation of the current object in its native Information about RubyGems can be found at: form. In this sense, Ruby is very similar to Python. DZone, Inc. |
  3. 3. 3 Essential Ruby tech facts at your fingertips Modules & Classes, continued RUby LANgUAgE REfERENCE TAbLES def Defines class method ... end The following reference tables provide a quick look at many elements of Ruby’s syntax. These can be used as a comparison def … to other languages in order to see how the syntax differs. end Ruby’s syntax is often rather different to that of, say, Java or C#. public Methods below are public/protected/ protected private private Types public symbol Methods with names supplied as symbols 123 Integer (Fixnum or Bignum) protected symbol are public/protected/private private symbol 12345 1.23e-4 Float attr symbols Creates accessor methods for all 0xFF00 0b01100 0244 Integer as hexadecimal, binary, or octal attr_accessor symbols variables given 1..5 'a'..'z' Range (inclusive attr_reader symbols attr_writer symbols 1...5 'a'...'z' Range (non-inclusive – e.g. 1…5 represents 1 through 4) alias :new_method_name :method_name Creates alias for method with name ?c Character super(arguments) Calls same method of superclass 'string' String "stringn" Double-quoted String with escape character Constants "string # {...}" Double-quoted String with inline expressions __FILE__ Filename of current source code file <<DOC Heredoc String string __LINE__ Current line DOC __END__ End of Ruby code (ignore everything below) :symbol Symbol DATA Anything below __END__ as an IO/File object /regexp/opts Regexp (regular expression) ENV[] Environment Variables [123, 'string', object, :symbol ] Array ARGV[ ] ARGF[ ] Command Line Arguments {1 => 2, :symbol =>'string' } Hash (associative array) Exceptions Literals begin Try a block of code and catch possible exceptions %q %Q(string) Single/double-quoted String ... rescue exception => variable %w %W(string string string) Array of Strings (no quotes for the Strings) ... %r(regexp) Regexp (regular expression) else ... ensure Variables ... end local Locally scoped variable @instance Instance scoped variable Figure 1 shows the Exception hierarchy. @@class Class scoped variable Exception $global Globally scoped variable Constant Constant NoMemoryError ScriptError Expressions LoadError if condition while condition ... NotImplementedError ... end end SyntaxError if condition ... until condition SignalException elsif condition ... ... end Interrupt else ... do StandardError end ... unless condition while condition ArgumentError ... else do IOError ... ... end until condition EOFError … if condition for object in enumerable IndexError … unless condition ... end LocalJumpError condition ? ... : ... (a ternary operator) break NameError case ... when condition next redo NoMethodError ... else retry RangeError ... end yield arguments FloatDomainError Modules & Classes RegexpError RuntimeError module Name Defines a module ... SecurityError end SystemCallError class Name < Super Defines a class with a superclass ... SystemStackError end ThreadError class << SomeClass Defines /accesses the singleton class of SomeClass— ... suited for defining class methods rather than TypeError end instance methods include Module Includes module in class ZeroDivisionError def name(arguments) Defines instance method SystemExit ... end fatal → DZone, Inc. |
  4. 4. 4 Essential Ruby tech facts at your fingertips Ruby Language Reference Tables, continued Ruby Core API, continued Ruby Tools The following is a selection of important Ruby Core API objects ruby The Ruby interpreter and methods. Instance methods are written .method and called irb An interactive Ruby prompt object.method while class methods are written #method and ri symbol Shows documentation for the specified symbol called Class.method. rdoc Generates HTML documentation form Ruby source files Object gem RubyGems, the Ruby package manager—not always available by default .class Returns the object’s class Ruby Interpreter Arguments .inspect Returns a string containing information -c Check code about the object -d Debug .instance_eval String code Evaluates a string or block in the context -e "…" Execute a single line expression .instance_eval { … } Block of the object -h Help .is_a? Class class Returns true if the object’s class equals -n gets loop .kind_of? Class class the argument -rLibrary require the specified library .methods Returns an array with the object’s methods -v Verbose mode .nil? Returns true if the object equals nil -w Display code warnings .respond_to? Symbol methodname Returns true if the object responds to -y Enable compiler debug mode the method -rubygems Loads RubyGem support .send Symbol methodname, Sends the message to the object along [arguments] with optional arguments Regular Expressions .to_s Returns a string of the object . Any character (excluding newlines) […] Any single character in set Enumerable [^…] Any single character not in set .all? { |object| … } Sends all elements to the block and * Zero or more returns true if every block returned true + One or more (to as many as possible) .any? { |object| … } Sends all elements to the block and +? One or more (to as few as possible) returns true if any block returned true ? Zero or one .map { |object| … } Sends all elements to the block and | (pipe symbol) Alternatives (e.g. a|b|c will match a, b, or c) returns a new Array with each result (…) Group ^ Beginning of line or string .find { |object| … } Sends all elements to the block and .detect { |object| … } returns the first element for which the $ End of line or string blocks result is not false {n, m} n to m (as a quantity) .find_all { |object| … } Sends all elements to the block and (?>…) Atomic group .select { |object| … } returns all elements for which the block (?=…) Lookahead is not false (?!…) Negative lookahead .grep Object pattern Returns a new Array with all elements for N Back reference N (where N is a digit) which pattern === element A Beginning of a string .include? Object object Returns true if the collection includes object b Word boundary B Non-word boundary .sort [{|object, object| … }] Returns the Array, sorted by each d Digit elements <=> or by the block D Non-digit s Whitespace Array (Enumerable) S Non-whitespace [] Fixnum index Returns the object at the specified index w Word-character (alphanumeric) [] Fixnum start, or all objects in the specified range [] Fixnum length W Non-word-character Range range z End of a string .compact Returns the Array without element that Z End of string, before newline equal nil /…/imx Case insensitive, multiline, ignore whitespace .delete Object object Deletes object from the Array .delete_at Fixnum index Deletes the object at index from the Array Ruby Core API .delete_if { |object| … } Deletes elements for which the block Figure 2 shows important Core API classes and their inheritance tree. returns true .each { |object| … } Sends each element to the block Module Class .flatten Flattens the Array Numeric Integer Fixnum .index Object object Returns the index of the first occurrence of object Range Float Bignum .insert Fixnum index, Inserts object at the position specified Object object by index .join String separator Returns a String with all elements Object String separated by separator .length Returns the number of elements Symbol .pop Returns the last element and removes it Array .push Object object... Pushes object to the end of the Array .reverse Reverses the order of elements Hash .rindex Object object... Returns the index of the last occurrence of object IO File .shift Returns the first element and removes it .uniq Returns a new Array without duplicates ... .unshift Object object... Pushes object to the front of the Array DZone, Inc. |
  5. 5. 5 Essential Ruby tech facts at your fingertips Ruby Core API, continued File < IO #basename String path [, String suffix] Returns the filename from path with or Hash (Enumerable) without suffix [] Object key Returns the value for key #exist? String filename Returns true if filename exists [] = value Object key Sets the value for key #join String piece [, String piece] Returns path by joining pieces .delete Object key Deletes key and value from the Array #new { |file| … } String filename, String options Opens and sends filename to block .delete_if { |key, value| … } Deletes key and value for which block #new String filename, String options Opens and returns filename returns true #size String filename Returns the filesize of filename .each { |key, value| … } Sends each key and value to the block .each_key { |key| … } Sends each key to the block File options .each_value { |value| … } Sends each value to the block r/r+ Read/read-write from start of file .include? Object object... Returns true if the hash includes a value w/w+ Write/read-write truncate if file exists or create new .key? Object object... for key a/a+ Write/read-write from the end of the existing file or create new .value? Object object... Returns true if the collection includes a key for value Struct .index Object object... Returns the key for value .each { |object| … } Calls the block for each instance variable .invert Returns a new Hash with keys and values passing the value inverted .each_pair Calls the block for each instance variable .keys Returns an Array with all keys from the Hash { |symbol, object| … } passing the name and value .length Returns the number of key-value pairs .length Returns the number of instance variables .merge Hash hash... Returns a new Hash with entries from .members Returns an Array containing all instance both Hashes variable names .select { |object| … } Returns an Array with key-value pairs for #new [Symbol name, ...] Creates a new Struct with an instance variable which the block returns true for each symbol .to_a Returns an Array with nested key-value pairs .values Returns an Array with all values from the Hash Kernel block_given? Returns true if a block was passed to the method String (Enumerable) fork { … } Creates a subprocess, runs the block in it and [] Fixnum index Returns the specified character or string returns its ID [] Range range open String filename Opens a file [] Regexp regexp open { |io| … } String filename Opens a file, passes it to the block and closes .capitalize Returns a capitalized version of the string it afterwards .center Fixnum width, Centers the string using spaces or a p Object object Prints object to the stdio [String filler] specified filler string printf String string, Formats and writes string to the stdio .chomp [String separator] Returns a String with separator removed from [Object object...] the end lambda {|object…| … } Creates and returns a new proc object with .count Returns the number of characters the supplied block .downcase Returns a lowercase version of the string puts String string Writes object to the IO .gsub Regexp regexp Replaces all occurrences of regexp with require String filename Load a Ruby file String replacement replacement system(string String command Executes a system command .gsub { |string…| … } Regexp regexp Finds all occurrences of regexp and replaces [,string…]) [, args] them with the result of the block .index String/Regexp piece Returns the position of the first occurrence of piece RUby 1.9 .rindex String/Regexp piece Returns the position of the last occurrence of piece Ruby 1.9 is the new version of Ruby considered transitional to .scan { |string…| … } Regexp regexp Scans the string for occurrences of regexp and passes them to the block Ruby 2.0 containing many changes to the language and libraries. .split String string Splits the string into an array and returns it It has an entirely new virtual machine and bytecode compiler, .strip Returns a string with whitespace removed formerly known as YARV. from both ends .swapcase Returns a version of the string with uppercase The new version includes support for unicode in strings, the turned to lowercase and vice-versa famous Oniguruma regular expression engine as well as .to_sym Returns a symbol named like the string Operating System Threads and Fibers for lightweight concurrency. .upcase Returns an uppercase version of the string Important syntax additions/differences to Ruby 1.8 IO Syntax Additions/ Ruby 1.9 Ruby 1.8 #read String filename [, Opens filename and reads at most Fixnum length] length bytes Differences #readline String file, [] Reads and returns a line from file Hash literal syntax { key: "value" } { :key => "value" } .close Closes the IO Additional Proc/lambda foo = ->(a,b){ … } foo = lambda { |a,b| … } definition syntax .each_line { |string| … } Send each line to the block Additional Proc/lambda call syntax foo.("x", "y")"x", "y") .eof? Returns true if there is no more data to read .print Object object Writes object to the IO Block local variables foo = lambda { |;a| ... } .printf String string, Formats and writes string to the IO Encoding support for String "foo".encoding [Object object...] String indices return Strings "foo"[2] # => 111 "foo"[2] # => "o" .puts Object object Writes object to the IO Optional arguments are def foo(a, b = 2, c, d = 3) .read [Fixnum length] Reads and returns at most length bytes possible before and after … .readline Reads and returns a line other arguments end .pos Returns the current position in bytes External Iterators i = [1, 2, 3].each DZone, Inc. |
  6. 6. 6 Essential Ruby tech facts at your fingertips Ruby Zone RESOURCES An interac tive online tutorial (no download or installation) The official Ruby website A Ruby news site The official documentation A community-powered Ruby news site The main Ruby repository A Ruby-related blog aggregator Wikipedia’s overview of Ruby JRuby (programming_language) (Java Ruby Implementation) The Ruby mailing lists IronRuby (.NET Ruby Implementation) AbOUT THE AUTHORS RECOmmENDED bOOK Melchior Brislinger Beginning Ruby is for every type Melchior Brislinger is currently a student of Visual Communication at the Bauhaus-University of reader wanting to learn Ruby, Weimar, Germany. He uses Ruby and other programming languages and tools to explore from novice programmers to web the possibilities of combining art, design and technology. developers to Ruby newcomers. It Peter Cooper starts by explaining the principles Peter Cooper is a digital “jack of all trades” based in the north of behind object-oriented programming, England. He is author of Beginning Ruby —published by Apress— builds toward creating a genuine creator of numerous Web sites and technologies, a professional blogger who runs Ruby Inside—the most popular blog for Ruby and Rails Ruby application, then explains key developers—and an entrepreneur who sold two startups in 2007. Ruby principles, such as classes and objects; projects, modules, and libraries; and other aspects of Ruby such as Publications Blog n Beginning Ruby, Apress database access. Projects Ruby Inside— Homepage Ruby Flow— bUy NOw Rails Inside— SwitchPipe— Get More FREE Refcardz. Visit now! Upcoming Refcardz: Available: Core Seam Essential MySQL Struts2 JUnit and EasyMock Core .NET Core CSS: Part III Getting Started with MyEclipse Very First Steps in Flex Hibernate Search Spring Annotations C# fREE Equinox Core Java Groovy Core CSS: Part II NetBeans IDE 6.1 Java Editor EMF PHP RSS and Atom XML Getting Started with JPA GlassFish Application Server JSP Expression Language JavaServer Faces Silverlight 2 ALM Best Practices Core CSS: Part I IntelliJ IDEA Design Patterns Published June 2008 HTML and XHTML Visit for a complete listing of available Refcardz. DZone, Inc. 1251 NW Maynard ISBN-13: 978-1-934238-21-9 Cary, NC 27513 ISBN-10: 1-934238-21-X 50795 888.678.0399 DZone communities deliver over 4 million pages each month to 919.678.0300 more than 1.7 million software developers, architects and decision Refcardz Feedback Welcome makers. DZone offers something for everyone, including news, $7.95 tutorials, cheatsheets, blogs, feature articles, source code and more. Sponsorship Opportunities 9 781934 238219 “DZone is a developer’s dream,” says PC Magazine. Copyright © 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, Version 1.0 or otherwise, without prior written permission of the publisher.