Saturday, January 29, 2005

Ruby, Chapter 1

These are notes I've taken while reading Programming Ruby:
Everything in Ruby is an object, no primitives.
No type definitions.
"puts" sends to standard out with new line
"print" or "printf" also used
"gets" assigns user input to (global var) $_


puts "Hello World"


Does not require semicolon delimitation, unless multiple statements on one line

def hoser
puts "Hello hoser"
end

Equivalent to

def hoser; puts "Hello hoser";end;


Ruby constructors executed as follows:

String.new("new string")

or

String.new()


Ruby returns the last expression evaluated in method (thus return statement is not necessary)
Method example:

def errMsg(msg)
result = "Error is #{msg}"
return result
end

OR

def errMsg(msg)
"Error is #{msg}"
end

Programming Ruby, The Pragmatic Programmers Guide states,"Ruby uses a convention to help it distinguish the usage of a name: the first characters of a name indicate how the name is used. Local variables, method parameters, and method names should all start with a lowercase letter or with an underscore. Global variables are prefixed with a dollar sign ($), while instance variables begin with an ``at'' sign (@). Class variables start with two ``at'' signs (@@). Finally, class names, module names, and constants should start with an uppercase letter. "

Arrays grow as needed, can contain object of different types:

arry = [ 9, 'hoser', 2.33 ]

you can dump the array contents with

arry

create an array like

arr1 = []
arr2 = Array.new
arr3 = %w{ stuff1 stuff2 stuff3 stuff4 hoser }

Hashes are similar to arrays but use braces, literal requires two objects for each entry (key value pair):

hoserMap = {
'hoser1' => 'bob',
'hoser2' => 'doug',
'hoser3' => 'hosehead',
'hoser4' => 'Jeremy'
}
puts "this is hoser1 #{hoserMap['hoser1']}"

If logic works like:

if isTrue
puts "true"
elsif isOtherTrue
puts "isOtherTrue"
else
puts "false"
end

Or another sneaky way:

puts "show this if true" if isTrue

while num<10
num = num*num
end
#OR
num = num * num while num<10


Code Blocks and Iterators
Pragmatic, "chunks of code that you can associate with method invocations, almost as if they were parameters. This is an incredibly powerful feature. You can use code blocks to implement callbacks (but they're simpler than Java's anonymous inner classes), to pass around chunks of code (but they're more flexible than C's function pointers), and to implement iterators"

Here's their example:

def callBlock
yield
yield
end

callBlock { puts "In the block" }

produces:

In the block
In the block

You can use blocks to implement iterators, by passing parameters between vertical bars (|):

arry = %w( wheat rice oats barley)
arry.each { |grain| puts grain}

outputs:

wheat
rice
oats
barley

Check out these looping constructs:

10.times { print "*" }
4.upto(20) {|i| print i}
('f'..'j').each {|char| print char}
#output:
**********4567891011121314151617181920fghij



No comments: