Ruby Cheatbook
Ruby Cheatbook
by David Black x = 100.to_s
x = 100 CODE BLOCKS
string = x.to_s
Compiled by Asyraf. Any code defined within {} or do end
{#code}
rubynerds.blogspot.com
COMPARING TWO VALUES OR
x == y do
Part 1 #code here
end
COMMENTING
The Basics #This is a comment!
LITERAL CONSTRUCTORS
ARITHMETIC FILE HANDLING Type Constructor Example
2 + 3
File writing “” or '' “abc” or 'abc'
2 – 3 String
2 * 3 fh = File.new(“filename.dat”, “w”)
: :symbol or
2 / 3 fh.puts x #x is imaginary variable here Symbol
fh.close :”symbol with spaces”
[] [1,2,3,4,5]
PRINTING TO THE SCREEN Array
puts “Hello” File reading {} {“New York” => “NY”
fh = File.read(“filename.dat”) Hash
print “Hello” “Oregon” => “OR”}
p “Hello”
.. or ... 0..10 or 0...10
Range
x = “Hello” EXTERNAL CODE INCLUSION
// /([a-z]+)/
puts x require “filename.rb” Regexp
print x Or
p x load “filename.rb”
SYNTACTIC SUGAR
GETTING INPUT FROM THE SCREEN STRING INTERPOLATION Arithmetic
gets x=1 Definition Calling example Sugared syntax
string = gets puts “x is equal to: #{x}”
def + (x) obj.+(x) obj + x
GLOBAL VARIABLES
BANG METHODS
Defined with the $ sign
The bang methods are defined with an exclamation '!'. $gvar = “This is a global variable!”
puts x if x > 10 Case matching can be customized for objects by defining Equivalent to classic do-while
the threequal function n = 1
If-else def ===(other_ticket) begin
if x > 10 self.venue == other_ticket.venue puts n
puts x end n = n + 1
else end while n< 11
puts “smaller than 10” #And this is case example for above def
end case ticket1
when ticket2 UNTIL STATEMENTS
If-elsif-else puts "Same venue as ticket2!" Opposite of while
if x > 10 when ticket3 n = 1
puts “x larger than 10” puts "Same venue as ticket3!" until n > 10
elsif x > 7 else puts n
puts “7 < x < 10” puts "No match" n = n + 1
elsif x > 5 end end
puts “5 < x < 7”
Or
else
LOOP STATEMENTS n = 1
puts “smaller than 5”
n = 1 n = n + 1 until n == 10
end
loop do puts "We've reached 10!"
n = n + 1
Unless – evaluates the opposite way as if break if n > 9
unless x > 10 FOR STATEMENTS
end
puts “x smaller than 10”
Or For every value in array
end celsius = [0, 10, 20, 30, 40, 50, 60]
n = 1
loop {