Sei sulla pagina 1di 5

Ruby Syntax  NUMBER TO STRING CONVERSION CODE BLOCKS

x = 100.to_s Any code defined within {} or do end
Cheatsheet x = 100 {#code}
string = x.to_s OR
(based on Ruby for Rails by David 
do
Black)
#code here
COMPARING TWO VALUES
Compiled by Ashraf @ rubynerds.blogspot.com end
x == y

Variables and Constants
The Basics COMMENTING
#This is a comment! CONSTANTS
ARITHMETIC Constants start with a capital letter
2 + 3 FILE HANDLING Constant = “Hi!”
2 – 3 File writing
2 * 3 fh = File.new(“filename.dat”, “w”) CONSTANT RESOLUTION IN NESTED CLASSES/MODULES
2 / 3 fh.puts x #x is imaginary variable here Class M
fh.close Module N
PRINTING TO THE SCREEN Class O
puts “Hello” File reading Class P
print “Hello” fh = File.read(“filename.dat”) X = 1
p “Hello” end
end
x = “Hello”
EXTERNAL CODE INCLUSION end
puts x require “filename.rb” end
print x Or
p x load “filename.rb” The constant is accessed by
puts M::N::O::P::X
GETTING INPUT FROM THE SCREEN STRING INTERPOLATION
gets x=1 VALUE TO VARIABLE ASSIGNMENT
string = gets puts “x is equal to: #{x}” x = 1
string = “Hello!”
EMBEDDED RUBY
STRING TO NUMBER CONVERSION
x = “100”.to_i
To embed Ruby code in HTML GLOBAL VARIABLES
<%#Ruby code in here%> Defined with the $ sign
string = “100” $gvar = “This is a global variable!”
x = string.to_i To 'print out' result of execution in HTML
<%=#Ruby code in here%>
INSTANCE VARIABLES
Refer to Instance Variables in Classes
Methods METHOD ACCESS RULES Objects
Access Rule Who can access
METHOD DEFINITION GENERIC OBJECT
def method1(x) Public Other objects can access obj = Object.new
value = x + 1
Private Only instances of object can 
return value
end access mthd on itself (self only) OBJECT 'SINGLETON' METHOD DEFINITION
def obj.method
Protected Only instances of object can 
puts “instance method definition”
METHOD ARGUMENTS access mthd on each other end
fixed number of arguments Here's 2 ways to define private/protected/#public 
def method(a,b,c) methods (private example only) #method call
method 1:  obj.method
variable number of arguments Class Bake
def method(*a) def bake_cake DEFAULT OBJECT METHODS
add_egg
default value for arguments respond_to? ­ Checks if methods by the name in 
stir_mix
def method(a, b=1, c=2) end argument are defined for the object
obj.respond_to?(“method1”)
combination arguments def add_egg
def method(a, b, *c) end send – Sends its arguments as 'message' to object (for 
method call)
NOTE: def method(a, *b, c) is not allowed! def stir_mix x = “method1”
end obj.send(x)

BOOLEAN METHODS #private definition object_id –Returns specific id of object


def ticket.available? private :add_egg, stir_mix obj.object_id
#boolean evaluation here end
end methods – Returns a list of methods defined for the 
method 2 object
Class Bake
SETTER METHODS obj.methods
def bake_cake
Refer to Setter Methods in Classes add_egg
stir_mix
end Classes

private CLASS DEFINITION


def add_egg class Ticket
end #class definition
end
def stir_mix
end
end
CLASS OBJECT DEFINITION SETTER METHODS INHERITANCE
tix = Ticket.new class Ticket Magazine inherits from Publications class
def initialize(venue) Class Magazine < Publications
@venue = venue #class definitions
INSTANCE METHOD DEFINITION
end end
class Ticket
def method #This is the setter method
#method definition def venue=(venue)
Modules
end @venue = venue
end end MODULE DEFINITION
end module MyModule
tix = Ticket.new #module definition
#This is how instance methods are called tix = Ticket.new(“Hall”) end
tix.method #This is how it's called
USING MODULES
tix.venue = “Field”
module MyModule
def function1
ATTR_* METHODS
CLASS METHOD DEFINITION end
class Ticket end
class Ticket
#This is a class definition #write only access
attr_writer :cost class Test
def Ticket.cheapest(*tickets)
include MyModule
#Class method definition
#read only access end
end
end attr_reader :price
#This is how to call on module functions
#read-write access test = Test.new
INSTANCE VARIABLES attr_accessor :venue test.function1
Defined with @ in front end
NESTING MODULES/CLASSES
@venue = “City”
tix = Ticket.new Nesting can be done like below
#This is how to access them Class M
CLASS/OBJECT INITIALIZATION tix.venue = “city” Module N
class Ticket tix.cost = 55.90 Module O
def initialize(venue) puts “the ticket price is #{tix.price}” Class P
@venue = venue end
end end
end ACCESSING CONSTANTS IN CLASSES end
Class Ticket end
tix = Ticket.new(“City”) Venue = “City”
end To create instance of Class P
p = M::N::O::P.new
#This is how it's accessed
puts Ticket::Venue To force absolute paths (search from top of #hierarchy
::P.new
Self puts “smaller than 10” end
end
#And this is case example for above def
WHAT IS SELF AT DIFFERENT LEVELS case ticket1
If­elsif­else
Location What self is if x > 10 when ticket2
puts “x larger than 10” puts "Same venue as ticket2!"
Top level main elsif x > 7 when ticket3
Instance method Instance of object calling the  puts “7 < x < 10” puts "Same venue as ticket3!"
method elsif x > 5 else
puts “5 < x < 7” puts "No match"
Instance method  Instance of class that mixes in  else end
in Module Module OR Individual object  puts “smaller than 5”
extended by Module end LOOP STATEMENTS
Singleton method The object itself n = 1
Unless – evaluates the opposite way as if
loop do
unless x > 10
n = n + 1
puts “x smaller than 10”
SELF AS DEFAULT MESSAGE RECEIVER end
break if n > 9
Class C end
def C.x puts “x smaller than 10” unless x > 10
#method definition Or
end n = 1
CASE STATEMENTS loop {
x #This is equivalent to self.x You can specify more than one condition for each  n = n + 1
end 'when' next unless n>9 #next skips to nxt
x = gets loop
case x break}

Control Flow when “y”, “yes” WHILE STATEMENTS


#some code
Equivalent to classic while statement in C
when “n”, “no”
IF AND FRIENDS n = 1
#some code
while n < 11
If  when “c”, “cancel”
puts n
if x > 10 #some code
n = n + 1
puts x else
end
end #some code
end
#OR
if x > 10 then puts x end
n = 1
n = n + 1 while n < 10
puts x if x > 10
puts "We've reached 10!"
If­else Case matching can be customized for objects by 
Equivalent to classic do­while
if x > 10 defining the threequal function
n = 1
puts x def ===(other_ticket) begin
else self.venue == other_ticket.venue puts n
n = n + 1 #argument sent to block thru |x| begin
end while n< 11 yield_an_arg {|x| puts "#{x}" } result = 100/n
rescue
Block returns argument puts “your number didn't work”
UNTIL STATEMENTS
def return_yielding exit
Opposite of while puts "code block will do by 10." end
n = 1 result = yield(3) puts result
until n > 10 puts "The result is #{result}."
puts n end For specific rescue, add Exception name
n = n + 1 return_yielding {|x| x * 10 } rescue ZeroDivisionError
end
Iteration within blocks                   Rescue in method definition
OR def temp(temps) def multiply(x)
n = 1 for temp in temps result = 100/x
n = n + 1 until n == 10 converted = yield(temp) puts result
puts "We've reached 10!" puts rescue ZeroDivisionError #begin x needed
"#{temp}\t#{converted}" puts “wrong value!”
FOR STATEMENTS end exit
end end
For every value in array 
celsius = [0, 10, 20, 30, 40, 50, 60,
celsiuses = [0,10,20,30,40,50,60,70]
70] RAISE
temp(celsiuses) {|cel| cel * 9 / 5 +
32 } def reraiser(x)
for c in celsius result = 100/x
puts "c\t#{Temperature.c2f(c)}" rescue ZeroDivisionError => e
end puts “Division by Zero!”
EACH STATEMENT raise e
YIELD STATEMENTS / ITERATOR
[1,2,3,4,5].each {|x| puts x * 10} end
Yield without arguments
Or
def demo_of_yield
[1,2,3,4,5].each do |x| puts x * 10 end
puts "Executing the method body..."
puts "Yield control to the block..." CREATING EXCEPTION CLASSES
yield class MyNewException < Exception
puts "Back from the block—finished!" end
end
raise MyNewException

demo_of_yield { puts "Now in block!”}


Exception Handling
Yield with arguments RESCUE
def yield_an_arg Begin/end wrapped method
puts "Yielding 10!" print “Enter a number:”
yield(10) n = gets.to_i
end

Potrebbero piacerti anche