Ruby Syntax Cheatsheet
Ruby Syntax Cheatsheet
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)