In this post I am sharing out a short and concise cheat sheet to help you learn or reminisce ruby syntax and constructs.
1. To print multiple Lines
print <<EOF
This is the first way of creating
here document ie. multiple line string.
EOF
2. To run in the beginning of program
BEGIN {
puts "Initializing Ruby Program"
}
3. To run at the end of the Program
END {
puts "at end"
}
4. Class in Ruby
class Customer
end
cust1 = Customer.new
5. Local variable start with lowercase or _
instance variable start with @
class variables start with @@
global variable start with $
6. When you plan to declare the new method with parameters, you need to declare the method initialize at the time of the class creation.
The initialize method is a special type of method, which will be executed when the new method of the class is called with parameters.
Here is the example to create initialize method −
class Customer
@@no_of_customers = 0
def initialize(id, name, addr)
@cust_id = id
@cust_name = name
@cust_addr = addr
@@no_of_customers+=1
end
end
cust1 = Customer.new("1","akash","Indiranagar")
7. In ruby methods are defined with def keyword and they are ended with end keyword
class Customer
@@no_of_customers=0
def display
puts "cust = #@@no_of_customers name = #@name"
end
def initialize(id,name)
@@no_of_customers+=1
@id = id
@name = name
end
end
cust1 = Customer.new("1","akash")
cust1.display
8. Constants in Ruby
class Example
VAR1 = 100
VAR2 = 200
def show
puts "Value of first Constant is #{VAR1}"
puts "Value of second Constant is #{VAR2}"
end
end
object = Example.new()
object.show
9. Arrays
ary = [ "fred", 10, 3.14, "This is a string", "last element", ]
ary.each do |v|
puts v
end
ary = ["akash",1,"foo","bar"]
ary.each_with_index do |k,v|
puts "#{k} , #{v}"
end
10. Hashmap
h = {"a" => 1 , "b" => 2}
puts h
h = {"a" => 1 , "b" => 2}
h.each do |k,v|
puts "#{k} => #{v}"
end
11. if/elsif/else
x = 1
if x > 2
puts "x is greater than 2"
elsif x <= 2 and x!=0
puts "x is 1"
else
puts "I can't guess the number"
end
12. Default agurments with method
def test(a1 = "Ruby", a2 = "Perl")
puts "The programming language is #{a1}"
puts "The programming language is #{a2}"
end
test "C", "C++"
test
13. Return in ruby can return one or more values
def test
i = 100
j = 200
k = 300
return i, j, k
end
var = test
puts var
It will return an array
14.Variable no of parameters
def sample (*test)
puts "The number of parameters is #{test.length}"
for i in 0...test.length
puts "The parameters are #{test[i]}"
end
end
sample "Zara", "6", "F"
15.Multiple Inheritence
module A
def a1
end
def a2
end
end
module B
def b1
end
def b2
end
end
class Sample
include A
include B
def s1
end
end
samp = Sample.new
samp.a1
samp.a2
samp.b1
samp.b2
samp.s1
Subclassing/Inheritance
Just add a < character and the name of the superclass to your class statement.
class BigBox < Box
# add a new instance method
def printArea
@area = @width * @height
puts "Big box area is : #@area"
end
end
16.Array declaration
a)nums = Array[1, 2, 3, 4,5]
b)nums = Array.new(20)
17.Accessing array element
num = arr.at(6)
18.Hashmap declaration
a)h = Hash.new
b) With defult value as "month" if key not present in hashmap
months = Hash.new( "month" )
puts "#{months[0]}"
puts "#{months[72]}"
c) H = Hash["a" => 100, "b" => 200]
d)h[1]="bar"
OR
h.store(1, "bar")
19.Exception handling
Put everything btw begin and end block ; everything between rescue and begin is protected
In an event that an exception does not match any of the error types specified, we are allowed to use an
else clause after all the rescue clauses.
begin
# -
rescue OneTypeOfException
# -
rescue AnotherTypeOfException
# -
else
# Any Other exceptions will be caght here
ensure
# Always will be executed
end
20. Class methods - can be called using classname.methodname
class Box
# Initialize our class variables
@@count = 0
def initialize(w,h)
# assign instance avriables
@width, @height = w, h
@@count += 1
end
def Box.printCount()
puts "Box count is : #@@count"
end
def self.printCount2()
puts "Box count is : #@@count"
end
end
# create two object
box1 = Box.new(10, 20)
box2 = Box.new(30, 100)
# call class method to print box count
Box.printCount()
Box.printCount2()
21. toString method in Ruby class
class foo
.....
def to_s
"(w:#@width,h:#@height)" # string formatting of the object.
end
22.Ruby does not have any access control over class/instance variables.
It has private,protected,public access specicifier for instance methods
add this to class
private :getWidth, :getHeight
23. attr_reader,attr_writer can be used to avoid declaring getter and setter methods respectively in class for instance variables
attr_accessor is combo of both
class Box
attr_accessor :w,:h
def initialize(a=10 , b=20)
@w = a
@h = b
end
end
Comments
Post a Comment