Monday, March 22, 2010

Ruby Notes


[Output]
"puts" writes to the screen with a carriage return at the end
"print" does the same thing without the carriage return

[Reading from the Console]
$name = STRDIN.gets

[Functions]
def welcome(name)
puts "hi #{name}" # "#{}" evaluate the variable
end


[Call Functions]
welcome("Mike") or welcome "Mike"

Extra arguments are gathered into the last variable if preceded with a "*"
def test(a=1,b=2,*c)

[Variable]
- Global variables start with '$'
- Class variables start with '@@'
- Instance variable start with '@'
- Local variables, method names, and method parameters start with lower case letter
- Class names, module names and constants start with uppercase letter
- Variable are composed of letters, numbers and underscrores
- Method Names may end with:
'?' - imply a boolean operation
'!' - imply something dangareous, like strings being modified
- __END__ on its own line with no white space, are ignored
- Lines between =begin and =end are ignored

[Collections]
- mystuff = %w{tivo nokia ipaq} # make a string array
- select # populates a new array with members which meet a criteria

[Loops]
for i in 1..4

[Regular Expressions]
- /a/ =~ # find first "a" and return position
- %r{a} =~ # same thing as above
- /p.r/ =~ # matches any character

[Blocks]
Blocks are nameless chunks of code that may be passed as an argument to a function.
def whereisit
yield
end
whereisit {puts "where is the money?" }


where is the money?

- each # iterated through each item of a collection
- detect # returns the first item matching a logical expression
- select # returns all items matching a logical expression
- collect # returns an array created by doing the operation on each element
- inject # is the reducer function in Ruby. "inject" loops over an enumerable and performs an operation on each object and returns a single value

[File I/O]
- Read File into a string:
file = File.new("myfile.txt")
mytext = file.read


- Read an entire file into an array of lines
lines = IO.readlines("data.txt")

- Read a file line by line
file = File.open("file.txt")
while line = file.gets
puts line
end
ensure
file.close # ensure that file is close
end

OR
IO.foreach("data.txt") { |line| puts line }


- Read only a few bytes at at time
require 'readbytes'
file = File.new("myfile.txt")
while bytes = file.readbytes(80)
print bytes+"\r\n"
end
file.close

No comments:

Post a Comment