Ruby's most commonly used method is probably each, an iterator that can act on an Array, Hash, Range, or any other array-like object. (It can also act on non-array like objects such as IO, in which case .each will iterate over each line).

There are four iterators built on top of each, called the Enumerable iterators. You can use them on any enumerable objects.

Method What it does

I discovered an interesting difference between two patch levels of the same Ruby (1.8.7)

def index
 respond_to do |format|
  format.html {
   super # call the index method of the superclass
  }
 end
end

This does not produce an error in Ruby 1.8.7 patchlevel 72 (the one that happens to ship with Snow Leopard), but in Ruby patchlevel 249 (the most recent one), it tells me I'm not allowed to do this.

Quick demonstration of public, private, and protected methods.

Reads a file line by line into an array my_stuff

my_stuff = []
file = File.new("config/random_categories.txt", "r")
while (line = file.gets)
my_stuff << line.chop!
end
file.close
my_stuff

Pass file to block

File.open("my_file.rb", "r") do |infile|
while (line = infile.gets)
puts "#{counter}: #{line}"
counter = counter + 1
end
end

Read File with Exception Handling

counter = 1
begin
file = File.new("readfile.rb", "r")
while (line = file.gets)
puts "#{counter}: #{line}"
counter = counter + 1
end
file.close
rescue => err
puts "Exception: #{err}"
err
end

Very quick rdebug primer for using the debugger in Mongrel.

<h1>Setting Up your Environment for Debugging</h1>

gem install ruby-debug

If you're in textmate go to Bundles > Bundle Editor > Edit Snippits… Add a new snippit like so:
[IMAGE:X]

<h1>How to Debug</h1>

1) Set a breakpoint in your code. Do this by typing "debug" followed by tab in TextMate. If setup correctly, TextMate will replace your debug statement with this:

A good area to spend some time for someone new to Ruby is to understand about objects. This serves as a basic wrap-around over view of what you need to know to get going.

First off remember to use the .class method on any object too (in your IRB, for example), giving you its class name. If you're playing along here, that'll help.

You will need to know what object orientation is in programming for this to make sense, and I hope it is geared to people coming from an object orientation learned in a different environment.

Everything in Ruby is an object. Even true and false have their own objects. Occasionally operators (like < < and ||) are language contructs, but that's really insignificant for the purpose of this lessen. When we say nearly everything in Ruby we mean everything you think is an object and then some.

Other languages have what are called primitives -- numbers, integers or floats; strings; booleans, etc. These things are see by the compiler and treated as what they are. But in Ruby all the primitives are objects too: numbers, strings, even boolean operators have their own classes.

So, you can do things like ask an object if it is a nil object. Since it is used to return a negative meaning to an operation or a non-result, it's a good way to catch edge cases. False and nil are trip-ups for programmers coming from other languages where because false does not evaluate to 0 and true doesn't eval to 1.

Ruby syntax for working with arrays (cheat-sheet):

def hilite_search_criteria(pattern, search_criteria)
return if pattern.nil? or search_criteria.nil?

pattern.gsub!(/(<[^>]*>)|\n|\t/s) {" "}

match_char = pattern =~ /#{search_criteria}/i
matched_string = $~.to_s

return if match_char.nil?
start = match_char – 25
start = (start < 0 ? 0 : start)

unless match_char.nil?
p = pattern[start ... match_char + search_criteria.length + 25]
match_char = pattern =~ /#{search_criteria}/i
p[match_char, matched_string.length ] = '' + matched_string + ""
return p
end
end

symbol what it does
+ concatenate
<< append
* repetition
[] indexing
<=> comparison, returns -1 for less, 0 for equal, 1 for greater
>> "a" <=> "b"
=> -1
>> "a" <=> "a"
=> 0
>> "b" <=> "a"
=> 1

Some more string methods, using examples:

>> s = "hello"
=> "hello"

>> s.concat(" world")
=> "hello world"
# .concat is same as +

1) Use the "system" method

system "ls"

2) Or use backticks. Note that backticks support you returning to the results and assigning them to a variable

res = `ls`

res now holds the directory listing returned by ls

© 2012 Tech Notes Suffusion theme by Sayontan Sinha