Everthing is an object. Objects created via a constructor. Standard constructor is “new”
item_one = LineItem.new
! and ? can be used in method names
method definition starts with def
def yourage ( dob )
#code goes here
end
use double colon (creates instance object)
Door::new( :oak )
you can print the an objects type/class
print 5.class # prints 'Integer'
print 'wishing for antlers'.class # prints 'String'
print WishMaker.new.class # prints 'WishMaker'
accessor methods are created for you.
attr_accessor :robot1 #creates get/set methods for robot1
attr_reader :robot2 #creates get method for robot1
attr_writer :robot3 #creates set method only
privacy is done like this
class Myclass
def m1 #public method
end
protected
def m2 #this method is protected
end
private
def m3 #this method is private
end
end
Hold collection of methods. Act as a namespace. Allow to share funcionality between classes. (
variables that begin with $ are global
$Chucky_bacon
variables begin with @ are instance variables
@my_chunky_bacon
class variables begin with @@
@@super_chunky_bacon
code blocks can be created with {/} or do/end
2.times { print "Hellow World" }
loop do
print "Another Hello"
print "World"
end
you can pass arguments to blocks using the | character
{ |x,y| x + y }
creates range of numbers or chars
(1..3) # numbers 1-3
('a'..'z') # letters a-z
(0...5) # numbers 0-4
Single quoted strings simply contain text, Double quoted strings allow for expression interpolation
print '2+2=#{2+2}' #returns> 2+2=#{2+2}
print "2+2=#{2+2}" #returns> 2+2=4
Double quoted strings that span multiple lines can we written using
%{This sentence
Spans
Lots
Of Lines}
concatenation operator, appends
email = "tom"
email << "@tomleo.com"
checks if method is nill. nill is an object.
print( if myfunction.nil?
"The Function is nill"
else
"The Function has value!"
end )
This is a method
if baconTastesGood.==(true)
#Yum
if baconTastesGood==(true)
#Yum
if baconTastesGodd
#Yum
a operation b
count += 1
price *= discount
count ||= 0 #count = count || 0
File::read("notefile.txt")
File::rename("oldfile.txt", "newfile.txt")
File::delete("newfile.txt")
File::open('notes.txt', 'w') #writes to new file
File::open('notes.txt', 'r') #reads from file
File::open('notes.txt', 'a') #adds to end of file
case grade
when 100
"A+"
when 90..99
"A"
when 80..89
"B"
when 70..79
"C"
when 60..69
"D"
when 0..59
"F"
end
=~ is the match operator to test strings against regular expressions
if line =~ /P(erl|ython)/
puts "What other scripting lanuage is work learning?"
end