KEMBAR78
Introducing Ruby | KEY
INTRODUCING RUBY
WHO IS THIS GUY?
   James Thompson
    @plainprogrammer
 james@plainprograms.com

Web Administrator & Student
  @ New Orleans Baptist
   Theological Seminary
WHAT IS RUBY?
 Ruby is a dynamic, open source programming language
with a focus on simplicity and productivity – ruby-lang.org
HISTORY
Created by Yukihiro “matz” Matsumoto

Started development in 1993

First public release in 1995 (Japan)

First English release in 1998

“make Ruby natural, not simple.”
CURRENT STATE
Legacy Stable: 1.8.7p72

Current Stable: 1.9.1p129

A community in transition

Alternatives to MRI
INSTALLING RUBY
•Windows: Cygwin is the best option. One-click installer
available but out of date.

•Linux: apt-get install ruby rdoc irb
•OS X: Already installed in 10.5. Available through
MacPorts as well.
LEARNING RUBY
RUBY’S COMMANDS

•ruby main interpreter
•irb interactive ruby shell
•ri ruby information, manpages for classes
•rdoc ruby documentation compiler
•erb ruby templating system
RUBY CONVENTIONS

•variable_name
•method_name
•ClassName
•ModuleName
•ConstantName | CONTSTANT_NAME
RUBY SYNTAX
OBJECT
ORIENTATION
                                   5.class         #=>   Fixnum
In ruby everything is an object.   3.9.class       #=>   Float
                                   "Hello".class   #=>   String
                                   Fixnum.class    #=>   Class
  This is both powerful and
                                   nil.class       #=>   NilClass
           different.
SYMBOLS

:a_symbol

opts = {
    :a_key => "Some value!",
    :another_key => "another value..."
  }
INSTANCE & CLASS VARIABLES


     @instance_variable
     @@class_variable
STRINGS
name = 'BarCamp Joe'
greeting = "Hello, #{name}!"

long_greeting <<-EOS
  Hello my old friend, #{name}!
  How have you been?
EOS

alternate_greeting = %{G'day, #{name.upcase}!}
NUMBERS

a   =   1
b   =   2.0
c   =   2.3e5
d   =   0x3F
e   =   0244
METHODS

def say_hello(name)
  result = "Hello, #{name}!"
end

puts say_hello("BarCamp NOLA")
METHODS

def say_hello(name)
  result = "Hello, #{name}"
  return result
end

puts say_hello("BarCamp NOLA")
CLASSES

class Greeter
  def say_hello(name)
    puts "Hello, #{name}!"
  end
end

doorman = Greeter.new

doorman.say_hello("BarCampers")
CLASSES

class RudeGreeter < Greeter
  def say_hello(name)
    puts ""
  end
end
CLASSES

class Greeter
  def initialize(name)
    @greeters_name = name
  end
end
CLASSES

class Greeter
  attr_reader :name
end

doorman.name
CLASSES

class RudeGreeter < Greeter
  def initialize(name, rudeness)
    @rudeness = rudeness
    super(name)
  end
end
MODULES

module Farewell
  def bid_farewell(name)
    "Good bye, #{name}!"
  end
end
MODULES

class Greeter
  include Farewell
end

doorman = Greeter.new("John")
doorman.bid_farewell("BarCampers")
CLASS/MODULE MUTABILITY

  class Numeric
    def plus(n)
      self.+(n)
    end
  end

  y = 5.plus 6    #=> 11
CONTROL STRUCTURES
 if "a" == "a"
   puts "a"
 end

 unless "a".nil?
   puts "a"
 end

 puts "a" unless "a".nil?

 name = case
   when num == 1: "one"
   when num == 2: "two"
   else
     num.to_s
 end

 [1,2,3].each do |value|
   puts value.to_s
 end
TYPES
•Numbers
•Strings
•Regular Expressions (/^(foo|bar)+$/)
•Arrays ([1,2,3])
•Hashes
•Ranges (1..10, "a"..."z")
•Symbols
BLOCKS, PROCS & LAMBDAS

  [1,2,3].each do |value|
    puts value.to_s
  end

  square = Proc.new do |n|
    n ** 2
  end
RUBYGEMS
CPAN      Pear   PECL              RAA   Rubyforge   Github     PyPI

17,000


12,750


 8,500


 4,250

                                 Obsolete
    0
                Perl             Ruby                Python            PHP




   PERL, PHP & RUBY PACKAGES
SEEING WHAT’S OUT THERE


  gem list --remote

  gem list
GETTING HELP


gem help
gem help commands
INSTALLING GEMS

gem install rails

gem install mysql sqlite3-ruby

gem install rails --no-ri --no-rdoc
COMMANDS FOR GEMS


rails --version
REMOVING GEMS


gem uninstall mysql
WHY USE RUBY?
QUESTIONS?
MORE RESOURCES

    ruby-lang.org
    ruby-doc.org
    rubygems.org
    rubyforge.org
    pragprog.com

Introducing Ruby

Editor's Notes

  • #4 * A dynamic object-oriented programming language * Inspired by Perl, Eiffel, Ada, Lisp and Smalltalk. * Its creator stated his goal was to &quot;make Ruby natural, not simple.&quot; Ruby is a very powerful language that is also very flexible. It is pervasively object-oriented. It is a general purpose language, so it is useful in the same places that Perl, PHP, etc. would be used.
  • #5 Developed by Yukihiro &quot;matz&quot; Matsumoto in 1993 with its first public release in Japan in 1995. It saw its first English announcement in 1998 and was followed by the publication of the Programming Ruby book in 2000 by Dave Thomas and Andy Hunt. The second edition of Programming Ruby, known as the &quot;Pickaxe Book&quot; was released in 2004.
  • #6 The Ruby world is transitioning to 1.9 and most major and currently maintained projects have made the switch to supporting 1.9. The community is tracking the progress of this transition with relation to Gems as isitruby19.com Beyond the &quot;official&quot; interpreter, usually referred to as &quot;MRI,&quot; there are a number of projects to develop alternative interpreters for various reasons and to met various needs. * Enterprise: Ruby 1.8 with better memory handling and other performance optimizations * JRuby: Ruby on top of the JVM, fastest 1.8 implementation around. * MacRuby: Ruby on top of Apple&apos;s Objective-C runtime. * IronRuby: Ruby on top of the .NET DLR. * Rubinius: Ruby developed with a tight C++ main interpreter and most of the rest of the language developed the Ruby subset understood by the main interpreter.
  • #7 If you are on Windows you should use Cygwin. Or, better yet, move to a unix environment since many of the best and most useful Ruby Gems use C extensions which are a pain to get working outside of a unix environment. There is the one-click installer as well, but it is badly outdated, and the straight binary releases from ruby-lang.org. For Linux you can use your favorite package manager to install ruby, irb and rdoc to get the whole base system. Some distros are starting to make 1.9 available but it usually has a suffix on all the commands which make them more cumbersome. For OS X if you have Leopard you already have Ruby available but if you use MacPorts you can get the latest version and even 1.9 with no suffix. Mac users also have access to the MacRuby project which is very promising and should eventually make OS X an even better platform for Rubyists. If you don&apos;t want to install Ruby you can play with an online interactive environment at tryruby.hobix.com.
  • #9 Ruby&apos;s command set provides a rich set of features for exploring the language, its documentation and different ways of using it.
  • #10 Ruby has a number of conventions which are collectively referred to as the &quot;Ruby Way.&quot; You are free to ignore these conventions if you like, but don&apos;t expect much love from your fellow Rubyists. And you can expect a nasty warning from the interpreter if you fiddle with what it expects of a constant, although you are actually free to change a constant. Module and Class names are actually constants which is why some consider it acceptable to use camel case for constants as well.
  • #12 One big thing to understand from the start with Ruby is that everything is an object. With the exception of reserved keywords everything is an object in Ruby. This allows for really interesting programming techniques in terms of chaining method invocation and even manipulation of parameters. Object is the parent of all classes. Duck typing is the pattern Ruby follows where behavior is closely coupled to type.
  • #13 Another big thing in Ruby are symbols. Because of Ruby&apos;s object model two strings which have the same character sequences are not the same. They have different object ids and occupy separate places in memory. Some have described symbols as immutable strings but this is really an oversimplification. Used with hashes for keys and as pseudo-constants. There is a lot more to symbols and whole blogs have focused on uses for symbols so go Google Ruby symbols if you want to learn more.
  • #14 If you are working with a class you have two special kinds of variables available to you. Instance variables are unique to a particular instance of an object while class variables are unique to all instances of a given class.
  • #15 Strings are really straight forward. Ruby supports single and double quoted strings, as well as HEREDOC style strings and alternative encapsulated strings. Strings also support interpolation of variables as well. Escaped new lines are optional when using certain ruby methods. Most of the time you don&apos;t need to be explicit with new lines, Ruby uses them where you would expect automatically.
  • #16 Ruby deals well with integers and floating point values as you would expect. It supports decimal and scientific notation as well as hex and octal.
  • #17 Something that is missing that some may wonder about is an explicit return. In Ruby the last expression within a method is returned as the result of the method by default. So explicit returns are not needed. You can do an explicit return however.
  • #20 A thing to note about Ruby classes is that they only support single inheritance, although there is an inheritance hierarchy at work in Ruby. Inheritance is also pretty straightforward to achieve.
  • #21 The way you call the constructor is by using the new method. To define a constructor for a class just define a method called initialize.
  • #22 You can also define attributes for classes. These are just set/get accessors for the class, if defined they are usually tied to an instance variable.
  • #23 You can invoke any inherited methods by calling super().
  • #24 Modules are collections of methods and constants. They are used to achieve much the same ends as multiple inheritance would provide but without the confusion.
  • #25 Modules get mixed in to classes using the include method.
  • #26 Something you should have noticed if you were following along with the code examples in irb is that I didn&apos;t redefine the entire class every time I did something new. One of the most useful and potentially troublesome features of Ruby is the open nature of classes and modules. You can just open them up and add to them. Heck, there are even ways to remove methods and the like. Here&apos;s an example of a modification to the way numbers work in Ruby. You can add and redefine methods on any class or module very easily in Ruby. Again, this is a very powerful but also dangerous capability.
  • #27 Ruby has all the typical control structures and some of its own interesting ones. That last one is a fun way to work with collections like arrays or hashes.
  • #28 Ruby has all the types you would expect from a good dynamic language. Most we&apos;ve already discussed but here&apos;s a quick rundown of the standard ones, including some we didn&apos;t talk about.
  • #29 Ruby supports closures in the forms of blocks, procs and lambdas. Blocks are basically pieces of code that you can pass as arguments to method calls. We saw a basic block with control structures. You can think of blocks like anonymous methods that are able to capture the context they are called in. Procs are essentially blocks that have been stored in a variable. This allows a the Proc to be more reusable than a block and allows the developer to avoid repetition. Ruby also provides lambdas which are similar to Procs but check the number of variables passed to them. For more on these three special structures in Ruby you can Google them and learn all the different ways they can be used.
  • #30 The best way to think of RubyGems is to think of it like CPAN for Ruby. It is the de facto standard for distributing reusable Ruby code. Lots of libraries, and most Ruby applications are distributed as Gems. You can get RubyGems either by default with Ruby 1.9 or downloaded from rubygems.org. But lets look at how you use RubyGems a little bit. Many Linux distros also have it available as a package.
  • #31 When compared to the package repositories of other popular languages Ruby is definitely a productive community. The numbers for Github may give a slightly exaggerated impression since many of the gems hosted with them are duplicates of gems distributed through Rubyforge or are unstable development packages. However, it is clear that Ruby is a healthy community of users sharing their work with one another.