Intro to Ruby: A Developer’s Quick Start

In Programming, Ruby by timfanelliLeave a Comment

Ruby is a very powerful, fun, and expressive language – I thought instead of continuing my sometimes long winded Intro To XXX series this morning, I’d post a cheat sheet of sorts to get you started writing Ruby code quickly.

Numbers

Ruby has three built-in types to support numeric values: Fixnum, Bignum, and Float. The names are pretty indicative of what they’re used for, Fixnum for fixed length integers, Bignum for infinite length integers, and Float for floating point numbers.

12345                           # Fixnum (decimal)
0x45DF				# Fixnum (hexadecimal)
04577				# Fixnum (octal)
0b11010010			# Fixnum (binary)
12345678901234567890		# Bignum

Fixnum stores values in a native machine word minus 1 bit. Values that can not be represented in this size are automatically converted to a Bignum instance.

Strings

Strings in Ruby may be either single or double quoted. Single quoted strings will not be evaluated in Ruby, other than two special back-slash notation expressions: \ and '. Double quoted strings will be evaluated for expression subsitution, and will obey back-slash notation the way most C, C++, and Java developers would expect.

puts 'This is my string.\n It does not look the way I think.\n'
puts "This is my string.\nIt looks just fine to me!\n"

Yields the following output:

This is my string.\n It does not look the way I think.\n
This is my string.
It looks just fine to me!

Expressions substitution in double quoted strings allows you to insert arbitrary values inline, instead of using string formatting syntax:

myname = "Timothy Fanelli"
myage = 25

intro1 = "Hello, my name is #{myname} and I am #{myage}."
intro2 = "Hello, my name is " + myname + " and I am " + myage.to_s + "."
intro3 = "Hello, my name is %s and I am %d." % [ myname, myage ]

intro1, intro2 and intro3 are all identical strings.

The third string is a general case of using Ruby’s builtin sprintf or format function, which look like this:

sprintf( formatstring, *args )
format( formatstring, *args )

Where you can pass any number of arguments in (they’ll be converted to an array called args), and formatstring can use the following conversion specifiers:

%b  Binary integer
%c  Single character
%d  Decimal integer
%e  Decimal integer displayed in exponential form
%f  Floating point number
%g  Same as %e if exponent is less than -4, %f otherwise
%o  Octal integer
%s  String
%u  Unsigned decimal integer
%x  Hexadecimal integer

You can substitute %E, %G and %X for %e, %g and %x respectively if you prefer capital letters in your notation.

Regular Expressions

Ruby has powerful builtin regular expression support. A regular expresion is expressed either as a pattern between delimiting forward-slashes, a pattern between an arbitrary delimiter preceded by a %r, or can be declared explicitly as a Regexp class instance, like so:

/pattern/
/pattern/im	# Regex with modifiers.
%r!pattern!
Regexp::new( "pattern", modifiers )

Any of these declarations can be treated as a Regexp instance. Calling Regexp::match( string ) will return a Match object or nil if the string does not match the pattern. Match objects can be indexed into if you used match groups in your regular expression.

Where ! in this instance could be replaced by either a matching pair of parenthesis, square or angle brackets or simpy two of any character of your choosing.

The following regular expression modifiers are supported:

i  Regexp::IGNORECASE  Case insensitive
x  Regexp::EXTENDED   Ignore whitespace and allow comments in regular expressions
m  Regexp::MULTILINE  Treat new lines as regular characters instead of whitespace
o                     Substitute only once

Methods

The general form for all Ruby method declarations is as follows:

def methodname ( parameterlist )
	method body
end

The parameter list can contain any number reference names, and can optionally have two special arguments indicated by an asterisk and ampersand respectively: *var and . Any excess parameters passed into a method beyond those explicity declared in the method’s parameter list will be converted to an array and passed in as var (or whatever you chose to name it). will be a Proc instance if a code block was specified, or nil otherwise.

Methods that support code blocks, such as List::sort, are called like so:

mylist = [ 'a', 'c', 'x', 'b' ]
mylist.sort { |a,b| a <=> b }

Where the sort method takes no explicit arguments, and only a Proc instance. This mechanism allows you to pass arbitrary code blocks into a method that can be executed repeatedly. This is comparable to C’s function pointers or C#’s delegate type. The arguments a and b between the vertical bars are the arguments to the Proc instance that will passed in when it is executed.

The return value of a method can be explicitly stated using a return statement. If return is omitted, then the method returns the value of the last expression evaluated.

Classes

You can define a class using the class keyword, and there’s built in support for your standard public, private and protected access control mechanisms:

class Fruit
public 
  def initialize( color )
      setColor color
  end

  def getColor
    @color
  end

protected
  def setColor( color )
    @color = color
  end

private
  def doSomething

  end
end

class Lemon < Fruit
  def initialize
    super 'yellow'
  end
end

mylemon = Lemon::new

In this case Lemon extends Fruit. Lemon::initialize is public by default because it’s not under any other access modifier. initialize is a special method that gets triggered when an object is instantiated using the built in new. super, when used in a method calls the parent class method of the same name. If no arguments are specified to super then the calling method’s arguments are passed in the same order to the parent class’ method. Finally, the @ prefix on a variable declares it as an instance variable of the class. An @@ prefix would declare it as a class variable, which is comparable to static variables in C++ objects and Java.

Modules

Modules are very similar to classes, except that they have no base class and can not be instantiated. Use the module keyword to declare a module, like so:

module Colors
  def convertToRGB( colorname )
    ...
  end
end

A class can include a module using a mechanism knowns as “Mix-ins”:

class Fruit
  include Colors

  initialize( color )
    @color = convertToRGB( color )
  end
end

Including a module makes its methods and properties available to your class.

Conclusion

So that’s where I’ll leave off for now. This is still just the very basics, but it should be more than enough to get you on your way to becoming a Ruby developer!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.