Refreshers, shortcuts of Ruby ...
name = 'Parm'
num = 1
name = "Parm"
"#{var_name}"
"hi"*5 = "hihihihihi"
myArray = []
myArray[1]
myArray[1] = "hi
myArray << "bye"
myArray.clear
ORmyArray = []
myHash = {}
myHash["key1"]
myHash["key1"] = "val1"
:test
true
OR false
1..10
, nuumbers from 1 - 10, including 101...10
, numbers from 1 to 9, not including 10(1..10).to_a
= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
alpha = 'a'..'m'
, alpha.include?('b')
-> true
TEST = 1
, all capsif condition
else
end
# can also be written as:
condition ? true (result) : false (result)
# Example
(5 < 4) ? puts "4 is greater than 5" : puts "No, 4 is not greater than 5"
# Multiple conditions
if condition1
elsif condition2
end
while condition do
end
# array could also be a range 0..5
for variable in array do
end
# unless is equivalent to if !(true)
unless (condition is false)
end
case test_value
when value
....
when value2
...
when value3
....
else
end
# create a method
def name
#...
end
# create method with args
def name_of_method(arg1)
#...
end
# defining a class
class NameOfClass #camelcased and 1st letter is capitalized
# Class methods should be defined above instance methods
def self.classMethod1
...
end
# Instance class
def method1
...
end
end
# create an instance
obj1 = NameOfClass.new
# call on the instance methods:
obj.method1
#call on a Class Method:
NameOfClass.classMethod1
@
and are called instance variables@name
getter
and setter
methods!#still inside of class declaration
#setter method
def name=(name)
@name = name
end
#getter method
def name
@name
end
# Outside of class:
parm = Person.new
parm.name = "Parm" #setting the name
parm.name #returns "Parm"
attr_accessor :name
attr_reader
and attr_writer
in case you just want a method to only set
or only retrieve an attributes value!initialize
MethodClassName.new
#inside of a class
def initialize(arg1, arg2, arg3)
@arg1 = arg1
@arg2 = arg2
...
end
[]
def [](arg)
end
class Parm
def []
"hello"
end
end
parm = Parm.new
parm[] # => "hello"
#same as
parm.[] # => "hello"
class << self
sub class
are CLASS METHODS
class Parm
class << self
def say_hi
"HI"
end
end
#SAME AS:
def self.say_hi
"HI"
end
def say_bye
"BYE"
end
end
# method say_hi can only be called by saying:
Parm.say_hi
#while method say_bye is called by an instance of that class:
Parm.new.say_bye