Ruby

Intro to Ruby - Classes

Ruby

Overview

So things are getting interesting now that we get to talk about the blueprint of objects which are classes. The code below is a simple example of a class which uses constant, local, instance, and class variables as talked about earlier. Demonstration of instance and class methods are also shown including the use of the initialize (constructor) method. Take some time to study and play with the code.

Code

# A simple class.
class Human
LABEL = "Human"

def initialize arms = 2, legs = 2
@arms = arms
@legs = legs
@@label = "This is the class label for a variable."
end

def describe
puts "I have #{@arms} arm(s)."
puts "I have #{@legs} leg(s)."
end

def self.label
@@label
end

def self.what_am_i
puts "I am a #{LABEL}."
end
end

# An instance of the Human class is created for the following examples.
human = Human.new 1, 2

# The following calls the "describe" instance method which, in turn, prints the values of the @arms and @legs instance variables.
puts "01 Instance Variables and Methods\n\n"
human.describe

# The following calls the "what_am_i" class method.
puts "\n02 Class Method\n\n"
Human.what_am_i

# The following prints the value of the LABEL contanst using accessed via the scope operator (::).
puts "\n03 Class Constant\n\n"
puts Human::LABEL

# The following is a convenience method to access the the class variable: @@label.
puts "\n04 Class Variable\n\n"
puts Human.label

Output

01 Instance Variables and Methods

I have 1 arm(s).
I have 2 leg(s).

02 Class Method

I am a Human.

03 Class Constant

Human

04 Class Variable

This is the class label for a variable.

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 09-classes.rb.

What’s Next

Modules

Tags:

Monday, March 2nd, 2009 Software No Comments

Intro to Ruby - Blocks

Ruby

Overview

Blocks, procs, and lambas (a.k.a. closures) capture code that remember the context in which it was defined, using that same context each time it is executed. Blocks are used often in Ruby programming and are definitely worth mastering. Besides the books mentioned earlier, you can also read more about them here. The following is only a brief look at the basics.

Code

# Example methods, scroll down to read more about how these methods are being used.

def proc_return
p = Proc.new {return "I am here..."}
puts p.call
"...but not here."
end

def lambda_return
p = lambda { return "I am here..." }
puts p.call
"...and I am here too."
end

def implicit_block
puts "Enter."
yield
puts "Exit."
end

def explicit_block &block
puts "Enter."
block.call
puts "Exit."
end

# Here we have a standard block of code that prints words from the "words" array.
puts "01 Blocks with do...end\n\n"
words = %w{one two three four five}
words.each do |word|
puts "[#{word}] "
end

# Here is another block of code, same as above, but using a more condensed syntax for blocks.
# NOTE: {} syntax takes precidence over do...end syntax and is great for one-liners and keeping your code condensed.
puts "\n02 Blocks with {}\n\n"
words.each {|word| puts "[#{word}] "}

# The following demonstrates a proc being created and returning a message. New procs, when returning, will exit their
# enclosing scope. Notice how the last string is not returned.
puts "\n03 Proc Return\n\n"
puts proc_return

# The following demonstrates a lambda being created and returned. Notice how returning from the lambda does not
# exit the enclosing method.
puts "\n04 Lamda Return\n\n"
puts lambda_return

# Demonstrates an implicit block call. Pay attention to the block being passed in and the "yeild" statement
# within the method.
puts "\n05 Implicit Block\n\n"
implicit_block {puts "In block."}

# Demonstrates call to the block as passed in as a parameter (BTW, it becomes a proc when parameterized).
puts "\n06 Explicit Block\n\n"
explicit_block {puts "In block."}

Output

01 Blocks with do...end

[one]
[two]
[three]
[four]
[five]

02 Blocks with {}

[one]
[two]
[three]
[four]
[five]

03 Proc Return

I am here...

04 Lamda Return

I am here...
...and I am here too.

05 Implicit Block

Enter.
In block.
Exit.

06 Explicit Block

Enter.
In block.
Exit.

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 08-blocks.rb.

What’s Next

Classes

Tags:

Friday, February 27th, 2009 Software No Comments

Intro to Ruby - Methods

Ruby

Overview

The following demonstrates the basics of defining and using methods through the def…end keywords. There are other ways to define methods but we won’t get into that for now. You might have guessed that you can use parenthesis when defining and using a method although, generally you don’t need them. For example, the following is valid syntax:

puts “Ruby”
puts(”Ruby”)

The same goes for method definitions.

Read on to learn more about methods.

Code

# Example methods, scroll down to read more about how these methods are being used.

def print_single value
puts value
end

def print_with_default value = "Unknown"
puts value
end

def print_variables label = "Unknown", *variables
puts "#{label}: #{variables.join ', '}"
end

def print_nil
end

def multi_return
return "one", "two", "three"
end

def last_return
v = 3 * 10
"I am the return value"
end

# The following method accepts one parameter (required) and then prints it.
puts "01 Single Value\n\n"
print_single "Heya"

# The following method also accepts one parameter but it is optional.
# In this case, passing no parameter results in the default value being printed.
puts "\n02 Default Value\n\n"
print_with_default

# The following method prints a labeled, variable-length array. The label is optional
# and the array can be any length in size.
puts "\n03 Variable Length Parameters\n\n"
print_variables "My Color Picks", "red", "black", "green", "blue", "violet"

# The following method does absolutely nothing but all Ruby methods return a value and, in this case,
# we get nil as the return value.
puts "\n04 Nil Return Value\n\n"
puts print_nil

# One handy feature is the ability to return multiple values. The following method demonstrates
# having multiple values returned. If you still have the "06-variables.rb" script handy, you might
# play with this more to see how you could assign these values to multiple variables. Don't be shy, give it a try!
puts "\n05 Multi-Return Value\n\n"
puts multi_return

# As mentioned above, a method always returns a value. The following method does some calculations but only
# a string is returned because it is the last statement listed in the method. Something to keep in mind
# when you are writing your own code.
puts "\n06 Last Return\n\n"
puts last_return

Output

01 Single Value

Heya

02 Default Value

Unknown

03 Variable Length Parameters

My Color Picks: red, black, green, blue, violet

04 Nil Return Value

nil

05 Multi-Return Value

one
two
three

06 Last Return

I am the return value

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 07-methods.rb.

What’s Next

Blocks

Tags:

Thursday, February 26th, 2009 Software No Comments

Intro to Ruby - Variables and Scopes

Ruby

Overview

The following demonstrates some variable basics in Ruby. Even though the examples below only use local variables here are a few things to know about variable scopes:

  • All variables are case sensitive
  • Global variables = begin with $
  • Local variables = lowercase
  • Constant variables = uppercase
  • Instance variables = begin with @
  • Class variables = begin with @@

More examples of how these variables are used will be in future posts.

Code

# The following demonstrates a simple representation of variables as references to objects.
puts "01 Variables are References\n\n"
v1 = "Ruby"
v2 = v1
puts "v1 = " + v1
puts "v2 = " + v2
v2.chop!
puts "v1 = " + v1
puts "v2 = " + v2

# The following shows mass assignment of multiple variables to a single object.
# NOTE: Assignment is done right-to-left with the 'y' variable starting the sequence.
puts "\n02 Right-to-Left Assignment\n\n"
r = u = b = y = "ruby"
puts "r = " + r
puts "u = " + u
puts "b = " + b
puts "y = " + y

# Another example of variable assignment but this time multiple objects are assigned to multiple variables.
puts "\n03 Parallel Assignment\n\n"
one, two = 1, 2
puts "one = " + one.to_s
puts "two = " + two.to_s

# A simple example of additive assignment.
puts "\n04 Additive Assigment\n\n"
x = 5
x += 1
puts x

# A simple example of subtractive assignment.
puts "\n05 Subtractive Assigment\n\n"
x = 5
x -= 1
puts x

Output

01 Variables are References

v1 = Ruby
v2 = Ruby
v1 = Rub
v2 = Rub

02 Right-to-Left Assignment

r = ruby
u = ruby
b = ruby
y = ruby

03 Parallel Assignment

one = 1
two = 2

04 Additive Assigment

6

05 Subtractive Assigment

4

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 06-variables.rb.

What’s Next

Methods

Tags:

Wednesday, February 25th, 2009 Software No Comments

Intro to Ruby - Hashes

Ruby

Overview

The following demonstrates the basics of Ruby hashes but there is much more to hashes so make sure to study the API.

The examples jump ahead a little as blocks are introduced via the use of brackets: {}. Brackets can both be used in the definition of a hash and a block of code. It is pretty cool to be able to write looping logic within one line of code isn’t it. More on loops soon but play with the hashes below first.

Code

# Basic initialization. The hash size is printed to show that the hash is new.
puts "01 Initialization\n\n"
h = Hash.new
puts h.size

# Another way to initialize a hash but with less typing. The hash size is printed to show that the hash is new.
puts "\n02 Alternative Initialization\n\n"
h = {}
puts h.size

# The following hash is initialized and then all the keys are printed.
puts "\n03 Hash Keys\n\n"
h = {:line_1 => "3030 Ruby Way", :city => "Colorado Springs", :state => "CO", :zip => 80808}
h.each_key {|key| puts key}

# Using the above hash, the values are printed instead.
puts "\n04 Hash Values\n\n"
h.each_value {|value| puts value}

# Using the above hash, the city value is found and printed.
puts "\n05 Grabbing Specific Values\n\n"
puts "City = " + h[:city]

# Using the above hash, the line_1 key and value is deleted.
puts "\n06 Deletion\n\n"
h.delete :line_1
puts h.inspect

# Using the above hash and a new hash (h2), we merge both into one and then print the result.
puts "\n07 Addition/Merging\n\n"
h2 = {:created_at => Time.now}
h.merge! h2
puts h.inspect

# Using the original hash, we clear it of all data and show that it is empty.
puts "\n08 Clearing\n\n"
h.clear
puts "Is hash empty?: " + h.empty?.to_s

Output

01 Initialization

0

02 Alternative Initialization

0

03 Hash Keys

line_1
city
state
zip

04 Hash Values

3030 Ruby Way
Colorado Springs
CO
80808

05 Grabbing Specific Values

City = Colorado Springs

06 Deletion

{:city=>"Colorado Springs", :state=>"CO", :zip=>80808}

07 Addition/Merging

{:city=>"Colorado Springs", :state=>"CO", :zip=>80808, :created_at=>Sun Feb 22 11:25:24 -0700 2009}

08 Clearing

Is hash empty?: true

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 05-hashes.rb.

What’s Next

Variables and Scopes

Tags:

Tuesday, February 24th, 2009 Software No Comments

Intro to Ruby - Arrays

Ruby

Overview

The following code demonstrates the basics of Ruby arrays and builds upon examples of strings, numbers, and ranges previously discussed. Be sure to download the code and play with arrays more yourself.

Code

# Basic initialization. The array size is printed to show that the array is new.
puts "01 Initialization\n\n"
a = Array.new
puts a.size

# Another way to initialize an array but with less typing. The array size is printed to show that the array is new.
puts "\n02 Alternative Initialization\n\n"
a = []
puts a.size

# An array can also be initialized via a range.
puts "\n03 Range Array\n\n"
puts (1..5).to_a

# An array can be initialized with comma separated values (in this case, an array of strings).
puts "\n04 String Array\n\n"
puts ["red", "green", "blue"]

# Another string array this time using the %W delimiter (which is basically using double quote notation).
# HINT: Use the %w delimiter for single quotes.
puts "\n05 Another String Array\n\n"
puts %W(red hot minute)

# Spend a little time playing with the following. Since a string is essentially an array of characters,
# you can always grab specific characters at will. The outputs various characters pulled from the
# alphabet string using arrays, ranges, and methods.
puts "\n06 Grabbing Specific Values\n\n"
alphabet = ('a'..'z').to_a
puts alphabet[1]
puts "
puts alphabet[0..5]
puts "
puts alphabet.at(2)

# The following initializes an array and then appends the word "end" to the original array.
puts "\n07 Appending\n\n"
a = %W(some random text)
puts a << "end"

# Using the above array, we remove the first element of the array.
puts "\n08 Shifting\n\n"
a.shift
puts a

# Using the above array, we remove the last element of the array.
puts "\n09 Popping\n\n"
a.pop
puts a

# Using what is left of the above array, we create a new array (b) and add them both together.
puts "\n10 Addition\n\n"
b = [1, 2]
puts a + b

Output

01 Initialization

0

02 Alternative Initialization

0

03 Range Array

1
2
3
4
5

04 String Array

red
green
blue

05 Another String Array

red
hot
minute

06 Grabbing Specific Values

b

a
b
c
d
e
f

c

07 Appending

some
random
text
end

08 Shifting

random
text
end

09 Popping

random
text

10 Addition

random
text
1
2

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 04-arrays.rb.

What’s Next

Hashes

Tags:

Monday, February 23rd, 2009 Software 2 Comments

Intro to Ruby - Ranges

Ruby

Overview

Ranges (either a .. or … notation) were one of the first new concepts that pulled me into the language and kept me reading, excited to see what I could do with the language next. Yeah, I know, crazy to think that a person could be reading a programming book with the same intensity as a thriller novel but, hey, Ruby does have that affect on people.

The following shows off ranges. Oh, and don’t let the for loop confuse you, I’ll be talking about them more in future posts. Just concentrate on how easy it is to create a range and the simplicity of the syntax.

Code

# An inclusive range includes the beginning and ending number in the range.
puts "01 Inclusive Range \n\n"
for x in 1..5 do
puts x
end

# An exclusive range includes the beginning but NOT the ending number in the range.
puts "\n02 Exclusive Range\n\n"
for x in 1...5 do
puts x
end

# Ranges can be used to extract portions of a string. In this example we pull the "ruby" word out of the string.
puts "\n03 Ranges used in a string.\n\n"
message = "My little ruby string."
puts message[10..14]

Output

01 Inclusive Range

1
2
3
4
5

02 Exclusive Range

1
2
3
4

03 Ranges used in a string.

ruby

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 03-ranges.rb.

What’s Next

Arrays.

Tags:

Friday, February 20th, 2009 Software No Comments

Intro to Ruby - Numbers

Ruby

Overview

Yesterday we learned about strings and today it is about numbers. The following is a breakdown of some of the basic things you can do with numbers.

NOTE: In order to output the various numbers to the console, the “to_s” (i.e. to string) method was used to concatenate the number with the string prefix. In some cases, parenthesis were used to achieve the desired output. Methods will explained more in future posts.

Code

# A simple fixnum.
puts "01 Fixnum: " + 1.to_s

# A simple decimal.
puts "02 Decimal: " + 2.5.to_s

# A more complicated decimal using scientific notation.
puts "03 Scientific Decimal Notation: " + 3.0e5.to_s

# A big number for very large numbers outside the range of a fix number.
puts "04 Bignum: " + 1234567890123.to_s

# A floated number at the maximum value.
puts "05 Float (Maximum): " + Float::MAX.to_s

# Another example of methods on a number chained with the to_s method.
# In this case we are asking if the number is zero or not (a boolean is returned).
puts "06 Method Example: " + 4.zero?.to_s

# Addition (using parenthesis to compute the value first and then calling the to_s method on the result).
puts "07 Addition: " + (2 + 3).to_s

# Subtraction (using parenthesis to compute the value first and then calling the to_s method on the result).
puts "08 Subtraction: " + (5 - 2).to_s

# Multiplication (using parenthesis to compute the value first and then calling the to_s method on the result).
puts "09 Multiplication: " + (7 * 2).to_s

# Division (using parenthesis to compute the value first and then calling the to_s method on the result).
puts "10 Division: " + (12 / 2).to_s

# A hex (base-16) number is prefixed with a 0x notation.
puts "11 Hex: " + 0x2F1.to_s

# A octal (base-8) number is prefixed with a 0 notation.
puts "12 Octal: " + 0252.to_s

# Underscores can be used to make numbers more readable. The result removes the underscores.
puts "13 Readability: " + 2009_02_11.to_s

Output

01 Fixnum: 1
02 Decimal: 2.5
03 Scientific Decimal Notation: 300000.0
04 Bignum: 1234567890123
05 Float (Maximum): 1.79769313486232e+308
06 Method Example: false
07 Addition: 5
08 Subtraction: 3
09 Multiplication: 14
10 Division: 6
11 Hex: 753
12 Octal: 170
13 Readability: 20090211

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 02-numbers.rb.

What’s Next

Ranges.

Tags:

Thursday, February 19th, 2009 Software No Comments

Intro to Ruby - Strings

Ruby

Introduction

You now know how to get started so lets take off the gloves and get our hands dirty.

Instructions

  • The number character(#) that proceeds any line of text in the code below is valid syntax for Ruby comments.
  • You will see the puts method used a lot below. It simply outputs each string to the console followed by a new line separator.
  • Each numbered example can be executed by copying and pasting the code in your IRB console window.
  • You can also run all numbered examples by downloading the code, unzipping the 01-strings.rb file and typing the following in a new command terminal (do not use IRB for this): ruby 01-strings.rb.
  • Again, the following is basic string manipulation in Ruby. There are plenty of methods on the Ruby string class that puts some languages to shame (yeah, I’m pointing a finger at you Java) that Ruby provides out of the box. If you don’t believe me, study the API of the String instance methods and that alone should put a smile on your face.

Code

# Double quotes.
puts "01 Hello, World"

# Single quotes.
puts '02 Hello, World'

# Double quotes but with a quoted string.
puts "03 'Hello, World!'"

# Double quote delimiter. All delimiters begin with a percent(%) sign.
puts %Q(04 Hello, World)

# Single quote delimiter.
puts %q(05 Hello, World)

# Double quotes with new lines
puts "06 Hello,\nWorld!"

# Computations using the #{expression} escape sequence.
puts "07 Multiplication: #{100 * 5}"

# Dates and Times. Another example of the #{expression} escape sequence.
# To learn more about date and time formatting via the strftime method, go here: http://apidock.com/ruby/Time/strftime
puts "08 Hello, World: #{Time.now.strftime('%B %d, %Y at %I:%M %p')}"

# String Concatenation (using the + method. Yeah, you read that right, a method NOT an operator.
# This is because everything in Ruby is an object!)
puts "09" + " Hello," + " World!"

# String Concatenation (using the << method - in this case we are appending each string to the previous string.)
puts "10 " << "Hello," + " World!"

# String Concatenation (using the an array. We'll discuss arrays soon enough so hang tight.)
puts ["11", "Hello,", "World!"].join(" ")

Output

The following is the output of the code listed above:

01 Hello, World
02 Hello, World
03 'Hello, World!'
04 Hello, World
05 Hello, World
06 Hello,
World!
07 Multiplication: 500
08 Hello, World: February 18, 2009 at 06:00 AM
09 Hello, World!
10 Hello, World!
11 Hello, World!

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 01-strings.rb.

What’s Next

Numbers.

Tags:

Wednesday, February 18th, 2009 Software No Comments

Intro to Ruby - Getting Started

Ruby

Overview

In order to get started, there are some resources you should have in hand. Plus we need to configure your environment so that you can begin writing and executing Ruby code. The following will help you get started. However, if you need the full gamut of info, check my Ruby page.

Literature

I recommend reading the following books and in this order:

  1. Mr. Neighborly’s Humble Little Ruby Book by Jeremy McAnally - Free. This is a great book for those new to the language. It is fast paced, to the point, and will get you up and running quickly.
  2. Programming Ruby 1.9: The Pragmatic Programmers’ Guide - $25. The defacto book of the Ruby language (a.k.a. The “Pickaxe” book) in some circles. You’ll be glad to have this book by your side even though it might take you a while to read through it all.

API

Every developer needs a set of API bookmarks for those times when you need to look up the obscure, here are mine:

  • Ruby Core API
  • Ruby Standard API
  • API Doc - Provides quick keyword search capabilities as well as community comments for Ruby and Ruby on Rails.
  • Got API - An alternative to API Doc but not as easy on the eyes. Depends on your temperament, of course.

…to be honest, I find API Doc to be my favorite source of info when I’m in a pinch. The rest are good backups. Up to you, of course.

News

Whether you are within the walls of a corporation or a lone wolf, here are a few feeds worth adding to your feed reader in order to stay connected with the community:

  • Ruby Inside - The inside scoop on Ruby news.
  • RubyFlow - A great site for picking up new resources to add to your development repertoire.
  • RubyFu - Useful quick news and resource links.

Tools

It takes very little to develop Ruby code. Using a simple text editor like TextEdit (MacOS) or Notepad (Windows) will do just fine for starters. However, you might consider the following tools as better alternatives to simple text editors:

  • TextMate - Lightweight, fast, and costs $30. For the MacOS platform only.
  • NetBeans - Developed by Sun and free to use. Works on multiple platforms.
  • Aptana - Adds Ruby on Rails support to the Eclipse IDE. Visit the software update site to install directly into Eclipse.

I am a MacOS guy, so TextMate is my development tool of choice when writing Ruby code. However, if you are not on the MacOS I would recommend Netbeans as it is less buggy than Eclipse (although I do like the Eclipse UI much better).

Installation

Installation and setup on the various operating systems is a breeze, all of which can be found on the Ruby Download page. That said, here is a quick guide of the major operating systems:

  • MacOS - For Tiger/Leopard users, Ruby already exists. Simply launch a terminal window and type irb on the command line and you can start executing Ruby code. Check out my MacOS Ruby Setup (Basic) post for additional configuration tips.
  • Linux - Check to see if you have Ruby installed first. Use the following command line: ruby -v. Otherwise, execute the following command: sudo apt-get install ruby irb rdoc. That’s it.
  • Windows - Download the one-click installer from Ruby Downloads page as mentioned above. Install and reboot after your are done. I’d suggest installing Ruby Gems and SciTE as well. You might need to download and install the zlib on your path if you experience gzip uncompression problems with Ruby Gems.

Command Line

Now that you have read up on Ruby and configured your environment, execute the following commands from a terminal/command window:

  1. ruby -v
  2. irb
  3. puts "Hello, World!"

The first line tells you what version of Ruby you have installed and confirms that Ruby exists on your system, the second line launches the Interactive Ruby Shell (IRB), and the last line executes your first line of Ruby code - which outputs “Hello, World!” back to the command line. Congratulations, you’ve just written your first Ruby program! Tomorrow, we’ll talk about strings.

Tags:

Tuesday, February 17th, 2009 Software No Comments