Source: http://www.fincher.org/tips/Languages/Ruby/
Welcome. You seem to have come here from a search engine. Your search words (ruby function) are highlighted on this page for your reading pleasure.
Ruby for the Attention Deficit Disorder Programmer - let's start learning Ruby fast!
1. Where to get Ruby
For windows you can download from http://rubyforge.org/frs/?group_id=167 for Linux try http://www.rpmfind.net (ruby comes with its own emacs mode, "ruby-mode.el").
2. Our first program
Enter the following into the file, "test.rb".
puts "Howdy!"
At the C: prompt enter,
C:>ruby test.rb
Produces:
Howdy!
OK, daylight's burning, let's move on.
3. Output in Ruby
"puts" writes to the screen with a carriage return at the end. "print" does the same thing without the carriage return. "printf" formats variables like in C and Java 5.
puts "puts works"
puts " with line breaks."
print "print works"
print " with no line breaks."
printf("\n\nprintf formats numbers like %7.2f, and
strings like %s.",3.14156,"me")
Produces:
puts works
with line breaks.
print works with no line breaks.
printf formats numbers like 3.14, and strings like
me.
4. Functions
1. Our first Ruby function
'def' starts the definition of a method, and 'end' ends it - no cute little curly braces. Parentheses are optional around the arguments we pass.
def welcome(name)
puts "howdy #{name}" # inside double quotes, #{ } will evaluate the variable
end
welcome "visitor"
This
Produces:
howdy visitor
2. How to return values from a function
we can use the faithful 'return'
def mult(a,b)
product = a * b
return product
end
puts mult(2,3)
This produces
==>6
Oddly enough you can leave out the "return" statement, and Ruby will helpfully return the last expression:
def mult(a,b)
product = a * b
end
puts mult(2,3)
or even simpler, leave out "product" and ruby returns the contents of the last expression:
def mult(a,b)
a * b
end
puts mult(3,3)
This produces
==>9
3. Optional argument values
Ruby lets you assign values to arguments which may, or may not be supplied as shown below:
def test(a=1,b=2,c=a+b)
puts "#{a},#{b},#{c}"
end
test
test 5
test 4, 6
test 3, 4, 6
This produces:
1,2,3
5,2,7
4,6,10
3,4,6
4. Extra arguments
Extra arguments are gathered into the last variable if preceded with a "*". ("each" is an iterator that loops over its members).
def test(a=1,b=2,*c)
puts "#{a},#{b}"
c.each{|x| print " #{x}, "}
end
test
test 3
test 3, 6
test 3, 6, 9, 12, 15, 18
This produces:
3,6
9, 12, 15, 18,
5. Variable naming tips:
1. Global variables start with '$'
2. Instance variables start with '@'
3. Class variables start with '@@'
4. Local variables, method names, and method parameters start with a lower case letter.
5. Class names, module names and constants start with an uppercase letter.
6. Variables names are composed of letters, numbers and underscores.
7. Method names may end with "?", "!", or "=". Methods ending with a "?" imply a boolean operation. Methods ending with "!" imply something dangerous, like strings being modified in place.
6. Interesting tidbits about Ruby,
1. '#' is the line comment character, all characters after this are ignored. Confusingly '#' can appear within quotes with a different meaning.
2. No semi-colons are needed to end lines, but may be used to separate statements on the same line
3. A backslash (\) at the end of a line is used for continuation
4. Indenting is not significant, unlike python
5. Types of variables do not need to be declared
6. Lines between =begin and =end are ignored
7. Lines following "__END__" on its own line with no white space, are ignored
8. A tiny demonstration of these:
# sample program showing special characters like comments
# I'm a comment line
a = 1 #notice no semicolon and no type declaration
b = 2; c = 3 #notice two statements on one line
name = "Abraham \
Lincoln" # a line continued by trailing \
puts "#{name}"
=begin
I'm ignored.
So am I.
=end
puts "goodbye"
__END__
1
2
3
4
Abraham Lincoln
goodbye
7. Quotes
Like in Perl, single quotes and double quotes have different meanings.
Double quotes means "please interpret special characters in this string". Things like backslash n ('\n') are converted to their typical values. The #{name} construct is converted to its value.
With single quotes, no special characters are interpreted.
Examples:
name="Mike"
puts "hi #{name}" ==>hi Mike
puts "hi\n #{name}" ==> hi (carriage return)Mike
puts 'hi\n #{name}' ==> hi\n #{name} (no substitutions are made since using single quote)
The braces are optional for global and instance variables
$myname="Ishmael"
puts "hi #$myname" ==>hi Ishmael
8. Objects
A great thing about Ruby is that numbers and strings are real objects.
1.5.floor() ==> "1"
returns the "floor" or next lower integer, "1"
parentheses in method calls are optional
"hello".upcase ==> "HELLO"
9. Collections
1. Arrays
An array of known object can be created by enclosing them in square brackets.
nums = [1, 2.0, "three"]
puts nums[2]
The above example prints "three", since Ruby arrays, like all right-thinking collections, are zero based.
You can use negative indexes to start from the end of the array
nums = [1, 2.0, "three", "four"]
puts nums[-1]
This will print "four". Using "-1" is much more concise than "nums[nums.length()-1]".
Since many arrays are composed of words and all those commas and quote marks are troublesome, Ruby provides a handy shortcut, %w:
mystuff = %w{tivo nokia ipaq} # make a string array
To get the count, or size, of an array, use the "length" method.
inspect - a convenient method to look at contents of an object. "p" is a shorthand for "puts obj.inspect"
myarray = [1,2,5,7,11]
puts myarray
puts myarray.inspect
p myarray
Produces:
1
2
5
7
11
[1, 2, 5, 7, 11]
[1, 2, 5, 7, 11]
Arrays can act like queues and sets
# & is the intersection operator
puts [1,2,3] & [3,4,5] # prints 3
# + is the addition operator
puts [1,2,3]+ [3,4,5] # prints 1,2,3,3,4,5
# - removes items from the first array that appear in the second
puts [1,2,3] - [3,4,5] # prints 1,2
# pop returns the last element and removes it from the array
alpha = ["a","b","c","d","e","f"]
puts "pop="+alpha.pop # pop=f
puts alpha.inspect # ["a", "b", "c", "d", "e"]
# push appends elements to the end of an array
alpha = ["a","b","c"]
alpha.push("x","y","z")
puts alpha.inspect # ["a", "b", "c", "x", "y", "z"]
# shift returns the first element and removes it from the array
alpha = ["a","b","c","d","e","f"]
puts "shift="+alpha.shift # shift=a
puts alpha.inspect # ["b", "c", "d", "e", "f"]
# unshift appends elements to the end of an array
alpha = ["a","b","c"]
alpha.unshift("x","y","z")
puts alpha.inspect # ["x", "y", "z", "a", "b", "c"]
2. Hashes
cars = {
'altima' => 'nissan',
'camry' => 'toyota',
'rx7' => 'mazda'
}
puts cars['rx7']
produces
mazda
You can also create Hashes with square brackets:
toppings = Hash["pancakes","syrup","Pizza","Pepper","Cereal","Sugar"]
puts toppings.inspect
Produces:
{"Pizza"=>"Pepper", "Cereal"=>"Sugar", "pancakes"=>"syrup"}
The "each" method is a wonderful way to iterate over the keys
toppings = Hash["pancakes","syrup","Pizza","Pepper","Cereal","Sugar"]
toppings.each{|key, value| puts "#{key} points to #{value}"}
Produces:
Pizza points to Pepper
Cereal points to Sugar
pancakes points to syrup
The "select" method populates a new array with members which meet a criteria
salaries = Hash["bob",10.9,"larry",7.5,"jimmy",6.0,"jerry",6.5]
salaries.inspect
mySalaryArray = salaries.select{|name,salary| salary > 7.0}
puts mySalaryArray.inspect
Produces:
[["larry", 7.5], ["bob", 10.9]]
3. Ranges
Ranges are composed of expr..expr or expr...expr. Two dots includes the last element, three dots excludes it.
('a'..'g').each{ |letter| puts letter }
Produces:
a
b
c
d
e
f
g
(1...3).each{ |num| puts num }
Produces:
1
2
10. Control Statements
1. if
income = 30000.00
if income < rate =" 0.02" rate =" 0.28" rate =" 0.5" grade =" 10" school =" case" top =" 6" lines =" IO.readlines(" i="0"> 5
puts i
i += 1
end
11. Statement modifiers
These are syntatic sugar
balance = -10.0
puts "Bankrupt" if balance < balance =" -10.0"> 0.0
f=2
puts f=f+2 while f < 10 ="=">4
==>6
==>8
==>10
12. Iterators
1. while
i = 0
while i < i =" i+1" n =" 10" animals =" %w(lions" n="0" max="7" fname =" fname" lname =" lname" person =" Person.new(">
which is true, but not helpful.
2. The "ToString" method, to_s
class Person
def initialize(fname, lname)
@fname = fname
@lname = lname
end
def to_s
"Person: #@fname #@lname"
end
end
person = Person.new("Augustus","Bondi")
print person
Produces:
Person: Augustus Bondi
3. Subclassing
In Ruby subclassing is done with the "<" character class Employee < position =" position" employee =" Employee.new(" position =" position" employee =" Employee.new(" position = "CEO" position =" position" position ="=" position ="=" employee =" Employee.new(" position = "CEO" position = "Engineer" i="0" lastname = "Croton" firstname = "Milo" rate =" 0.15" mytip =" tip(10.0)" file =" File.new(" mytext =" file.read" lines =" IO.readlines(" file =" File.open(" line =" file.gets" file =" File.open(" line =" file.gets" file =" File.new(" bytes =" file.readbytes(80)" file =" File.new(" bytes =" file.readbytes(80)" mathwiz =" MathWiz.new" file =" File.new(" doc =" REXML::Document.new" class="'entry']">ruby -e 'sleep 2'
c:\home\mfincher>ruby -e 'puts 3*4'
12
c:\home\mfincher>ruby -e 'puts 3*4; puts 4*4'
12
16
26. Editing files in place
Ruby offers a simple way to make a string substitution in many files all at once with a single line of code. The "-p" option loops over the files, the "-i" is the backup extension. With this command we are changing all the documentation from version 1.5 to 1.6, but the original files are renamed to ".bak".
C:\home\mfincher\ruby>more v2.txt
Regarding version 1.5 ...
....
version 1.5 is easy to install
C:\home\mfincher\ruby>ruby -pi.bak -e "gsub(/1.5/,'1.6')" v*.txt
C:\home\mfincher\ruby>more v2.txt
Regarding version 1.6 ...
....
version 1.6 is easy to install
C:\home\mfincher\ruby>more v2.txt.bak
Regarding version 1.5 ...
....
version 1.5 is easy to install
27. Example of printing duplicate lines in sorted file.
#prints duplicate lines in sorted files in the file passed in as first arg
file = File.open(ARGV[0])
lastLine = ""
counter = 0
while line = file.gets
counter += 1
if lastLine == line
puts "#{counter-1}: #{line}#{counter}: #{line}\r\n"
end
lastLine = line
end
puts "done. Processed #{counter} lines"
28. Ruby has its own interpreted shell, irb.
C:\home\mfincher>irb
irb(main):001:0> puts "Hello World"
Hello World
=> nil
irb(main):002:0> a=1
=> 1
irb(main):003:0> a*2
=> 2
irb(main):004:0>
29. ruby can take input from stdin
echo 'puts "hello"' | ruby
30. to pass a string on the url it needs to be "escape"'d first.
require 'uri'
...
URI.escape("some string...")
31. Example to remove "funny" characters from a filename
Example of iterating over the filenames in a directory, using regular expression substitution in strings, and renaming files.
#replaces any "funny" characters in a filename in the current directory with an underscore
#if the new file name already exists, this skips it.
Dir.foreach(".") { |f|
print "testing \"#{f}\""
if f =~ /[^\w\-\.]/ #filename contains something other than letters, numbers, _,-, or .
puts "\r\n name with funny characters: #{f}"
newName = f.gsub(/[^\w\.\-]/,"_") # \w is any word character, letter,num or _
if File.exist?(newName)
puts " File #{newName} already exists. Not renaming."
else
puts " renaming #{f} to #{newName}"
File.rename(f,newName)
end
else
puts " it's ok."
end
}
32. Looping over list of arguments
ARGV.each {|f|
puts f
counter = 0
file = File.open(f,"r")
ftmp = f+".tmp"
tmp = File.open(ftmp,"w")
while line = file.gets
if line =~ /pid="2"/
counter += 1
line = line.gsub(/pid="2"/,"pid=\"#{f}:#{counter}\"")
puts line
end
tmp.print line
end
file.close
tmp.close
puts "renaming #{ftmp} to #{f}"
File.rename(ftmp,f)
}
33. Miscellanous Commands
command description example result
global_variables returns all global variables
local_variables returns all local variables
sleep seconds sleeps specified seconds
rand returns a random number between 0 and 1
rand(max) returns int between 0 and max
warn like print, but writes to STDERR
Interesting string functions
command description example result
center centers string "City".center(20) "________City________"
ljust left justifies "State".ljust(30) "State_________________________"
rjust right justifies "State".rjust(30) "_________________________State"
gsub global regex replacesments "this is a test".gsub(/[aeiou]/,'_\1') th_s _s _ t_st
tr translates "The greatest of these is".tr('aeiou','*') Th* gr**t*st *f th*s* *s
each splits and iterates "one:two:three".each(':'){|x| puts x}
one:
two:
three
34. DateTime
puts DateTime.now #prints 2006-11-25T14:26:15-0600
puts Date.today #prints 2006-11-25
puts Time.now #prints Sat Nov 25 14:29:57 Central Standard Time 2006
35. Introspection with ObjectSpace
You can find all the objects in your program of a particular type using ObjectSpace.each_object.
class Person
def initialize(name,age)
@name = name
@age = age
end
attr_reader :name
end
p = Person.new("Alfred",34)
p2 = Person.new("Janie",31)
ObjectSpace.each_object(Person) {|s|
puts s.name
}
Produces:
Janie
Alfred
36. Testing
Ruby comes right out of the box with a testing framework. Here's a quick example:
require 'test/unit'
class TestMe < s =" 1" canvas2 =" TkCanvas.new(root)"> 'top', 'fill'=>'both', 'expand'=>'yes')
points = []
end
TkcLine.new(canvas2, 0,0,100,100)
end
Tk.mainloop
39. irb - interactive ruby
Ruby comes with an REPL (Read Eval Print Loop) utility to let you try ruby interactively. ("inf-ruby.el" provides an internal shell in emacs for irb).
C:>irb
irb(main):001:0> puts "hello"
puts "hello"
hello
nil
irb(main):002:0> Object.methods
Object.methods
["send", "name", "class_eval", "object_id", "new", "singleton_methods", "__send__", "private_method_defined?", "equal?", "taint", "frozen?", "instance_variable_get", "constants", "kind_of?", "to_a", "instance_eval", "require", "ancestors", "const_missing", "type", "instance_methods", "protected_methods", "extend", "protected_method_defined?", "eql?", "public_class_method", "const_get", "instance_variable_set", "hash", "is_a?", "autoload", "to_s", "class_variables", "class", "tainted?", "private_methods", "public_instance_methods", "instance_method", "untaint", "included_modules", "private_class_method", "const_set", "id", "<", "inspect", "<=>", "==", "method_defined?", ">", "===", "clone", "public_methods", "protected_instance_methods", "require_gem", ">=", "respond_to?", "display", "freeze", "<=", "module_eval", "autoload?", "allocate", "__id__", "=~", "methods", "gem", "method", "public_method_defined?", "superclass", "nil?", "dup", "private_instance_methods", "instance_variables", "include?", "const_defined?", "instance_of?"] irb(main):003:0>
40. RubyGems a ruby package installer
You can download RubyGems from http://rubyforge.org. Unzip the files (eg, C:\opt\ruby) then install by entering:
C:>cd C:\opt\ruby\rubygems-0.9.0
C:\opt\ruby\rubygems-0.9.0>ruby setup.rb all
41. Ruby on Rails
1. How to write a log message
You can use logger's methods "warn", "info", "error", and "fatal".
logger.info("request.remote_ip"+request.remote_ip);
2. Field names ending with "_at" are assumed to be datetime fields and are filled in automagically by rails for ActiveRecord objects. The suffix "_on" are assumed to be dates.
3. Console
to dubug applications it's convenient to use the console script
myapp>ruby script/console
4. debug method
You can use the debug() method inside web pages to dump info about an object.
Thanks for visiting
<%= debug(@myobject) %>
5. Active record notes
1.
Find all records meeting a criteria
def self.suitable_jokes(sort_key)
if sort_key == "Newest"
find(:all,
:conditions => "suitable = \"1\"",
:order => "entry_date DESC"
)
elsif sort_key == "Worst"
find(:all,
:conditions => "suitable = \"1\"",
:order => "entry_date ASC"
)
else
find(:all,
:conditions => "suitable = \"1\"",
:order => "current_rating DESC"
)
end
end
The first argument to find can also be ":first" or ":last".
2. Find the count of records meeting a criteria
def self.waiting_jokes()
count("suitable = \"0\"")
end
def self.total()
count("suitable = \"1\"")
end
Find the total number of items
count = Joke.count
Find the total number of items meeting a criteria
count = Joke.count(["suitable = \"1\""])
3. Pagination
The ":limit" and ":offset" options allow easy pagination.
To return the fifth page of items use the following:
find(:all,
:conditions => "suitable = \"1\"",
:order => "current_rating DESC",
:limit => 10,
:offset => 40
)
4. Use raw SQL and return two values
def getAverageRatingAndCount
record = Rating.find_by_sql(["select count(*) as count,avg(rating) as average from ratings WHERE joke_id = ?",id]);
return record[0].average.to_f , record[0].count.to_i
end
5. The "create" method in ActiveRecord will do "new" and "save" operations simultanously.
mydog = Dog.create(
:name => "Fido"
:breed => "Collie"
)
42. Ruby Quotes:
"Ruby is a language for clever people." -Matz
"Ruby is the perlification of Lisp." -Matz
"Java is a pair of scissors, Ruby is a chainsaw." -Mitch Fincher
"Type Declarations are the Maginot line of programming." -Mitch Fincher
Thursday, September 20, 2007
Ruby Language
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment