Concepts for Ruby
Ruby is a dynamic, object-oriented programming language known for its simplicity and productivity. Created by Yukihiro Matsumoto (Matz) in the mid-1990s, Ruby emphasizes developer happiness and ease of use. Its syntax is elegant and expressive, resembling natural language, which contributes to its readability and maintainability. Ruby offers features such as dynamic typing, automatic memory management, and a powerful standard library. It also has a vibrant ecosystem of third-party libraries and frameworks, including Ruby on Rails for web development. Ruby's focus on developer convenience, combined with its flexibility and scalability, has made it popular for building web applications, scripting tasks, and automation.
Print Text
puts "Hello World!" print("Hello World!")
Comments
# one line comment =begin multi line comment =end
Variables
carCount = 2 name = "Joe" isPurple = true
Data Types
carCount = 2 age = 15 seaLevel = -10000 usBudget = 11000000000 lightSpeed = 11799312874 myGPA = 3.45 piValue = 3.14159265 lastLetter = "Z" isMale = true myName = "Joe"
Math Op
carCount = 6; truckCount = 3; total = carCount + truckCount puts total subtract = carCount - truckCount puts subtract multiple = carCount * truckCount puts multiple divisible = carCount / truckCount puts divisible # performs division and gets remainder which is 0 modulo = carCount % truckCount puts modulo
Math Functions
power = 3.pow(6) puts power root = Math.sqrt(16) puts root floorVal = 3.14.floor() puts floorVal ceilVal = 4.3.ceil() puts ceilVal roundVal = 3.4.round() puts roundVal # random number from 0 to 100 ranNum = rand(0..100) puts ranNum
If/Else
carCount = 6; if carCount > 3 puts "More than three cars" elsif carCount == 3 puts "Equal to three cars" else puts "Less than three cars"
Ternary
carCount = 3 result = carCount > 2 ? "Yes" : "No" puts result
Switch
$carCount = 3 case $carCount when 1 puts "One car" when 2 puts "Two cars" when 3 puts "Three cars" else puts "More than three" end
Functions
def handleCars(cars, wheels) total = cars * wheels; return total end result = handleCars 3, 4 puts result
Interpolation
name = "Joe" car = "Mazda" result = "#{name} drives a #{car}" print(result)
Type Casting
def squareA(length) result = length ** 2; return result.to_s; end squareL = "4" convertedVal = squareL.to_i area = squareA(convertedVal) print(area)
Date and Time
# current date date = Time.now puts date # epoch time milliseconds = Time.now.to_f puts milliseconds # current year year = Time.now.year puts year # current month month = Time.now.month puts month # formatted date day = Time.now.day formatted = "#{month}/#{day}/#{year}" puts formatted
Classes
class Cars def initialize @carList = [] end def addCar(name) @carList << name end def removeFirst() @carList.shift() end def getFirstVal() if @carList.length > 0 return @carList[0] end return '' end end newList = Cars.new newList.addCar("Honda") newList.addCar("Mazda") newList.addCar("Toyota") newList.removeFirst() firstCar = newList.getFirstVal() puts firstCar
Inheritance
class User def initialize(username, password) @username = username @password = password end end class Admin < User def initialize(username, password, id) super(username, password) @id = id end def getUsername() return @username end def getAdminID() return @id end end newAdmin = Admin.new("alpha0", "pw1", "1FE") puts newAdmin.getUsername() puts newAdmin.getAdminID()
Method Overload
// No Native Support or Implementation
Abstract Class
// No Native Support or Implementation
Static Class
class Helper class << self def circleA(radius) return 3.14 * (radius ** 2) end def squareA(length) return length ** 2 end end end puts Helper.circleA(3) puts Helper.squareA(4)
Arrays/Lists
names = Array["Joe", "Alex", "Bob"] names[1] = "Alex" name = names[1] numItems = names.length puts name puts numItems
Array Methods
cars = ["Honda", "Mazda", "Toyota"]; # number of elements in array puts cars.length # first element of array puts cars.first # last element of array puts cars.last # new array with first 2 elements array1 = cars.take(2) puts array1 # drops the 1st element from array array2 = cars.drop(1) puts array2 # removes the first element cars.shift() puts cars.first # adds as new first element cars.unshift("Ford") puts cars.first # deletes at index 0 cars.delete_at(0) puts cars.first # checks for value Mazda puts cars.include?("Mazda")
Concatenation
carsListKr = ["Kia", "Hyundai", "Daewoo"] carsListJp = ["Honda", "Mazda", "Toyota"] combined = carsListKr.concat(carsListJp) printf(combined[1] + "\n") printf(combined[4])
Sort Method
ages = [5, 3, 1, 6, 7, 4, 19] ages.sort puts ages
Objects
class User attr_reader:first,:last,:carBrands def initialize( first, last, age, retired, carBrands ) @first = first @last = last @age = age @retired = retired @carBrands = carBrands end def getVal(val) return val end def fullName() return "#{first} #{last}" end end brands = Array["Mazda", "Toyota"] user = User.new( "Joe", "Doe", 23, false, brands ) puts user.first puts user.carBrands[1] puts user.fullName()
Maps (Key/Value)
carMap = Hash.new carMap["Joe"] = "Toyota" carMap["Bob"] = "Mazda" carMap["Tom"] = "Ford" puts carMap["Tom"] carMap.delete("Tom") puts carMap.include?("Tom")
Sets
require 'set' cars = Set.new cars.add("Mazda") cars.add("Toyota") cars.add("Honda") puts cars.include?("Honda") cars.delete("Honda") puts cars.include?("Honda")
Stack
cars = [] cars << "Mazda" cars << "Toyota" cars << "Honda" puts cars[cars.length - 1] cars.pop() puts cars[cars.length - 1]
Queues
cars = [] cars << "Mazda" cars << "Toyota" cars << "Honda" puts cars[0] cars.shift() puts cars[0]
Linked List
class Node # full access to class properties attr_accessor :value,:next def initialize(value, nextVal = nil) @value = value @next = nextVal end end class LinkedList attr_accessor :head def initialize @head = nil end def add(value) newNode = Node.new(value) if @head == nil @head = newNode else current = @head while current.next != nil current = current.next end current.next = newNode end end def returnHead() return head.value end def traverse() current = head while current != nil print(current.value + "\n") current = current.next end end end carList = LinkedList.new() carList.add("Mazda") carList.add("Toyota") carList.add("Honda") puts carList.returnHead() carList.traverse()
Graphs
class Graph def initialize @graphMap = Hash.new end def addNode(value) @graphMap[value] = [] end def addVertices(node1, node2) if @graphMap.include?(node1) == false @graphMap[node1] = [] end if @graphMap.include?(node2) == false @graphMap[node2] = [] end @graphMap[node1] << node2 @graphMap[node2] << node1 end def breadthTraverse(start) queue = [start] visited = Hash.new visited[start] = true; while queue.length > 0 currentVal = queue.shift() puts currentVal tempArr = @graphMap[currentVal] for tempVal in tempArr do if visited.include?(tempVal) == false queue << tempVal visited[tempVal] = true end end end end def depthTraverse(start) stack = [start] visited = Hash.new visited[start] = true; while stack.length > 0 currentVal = stack.pop() puts currentVal tempArr = @graphMap[currentVal] for tempVal in tempArr do if visited.include?(tempVal) == false stack << tempVal visited[tempVal] = true end end end end end newGraph = Graph.new newGraph.addNode("a") newGraph.addVertices("a", "b") newGraph.addVertices("a", "c") newGraph.addVertices("b", "d") newGraph.addVertices("b", "e") newGraph.addVertices("d", "f") newGraph.addVertices("d", "g") newGraph.addVertices("d", "h") newGraph.addVertices("e", "i") newGraph.addVertices("e", "j") newGraph.breadthTraverse("a") newGraph.depthTraverse("a")
For Loops
names = ['Joe', 'Alex', 'Bob']; for name in names do puts name end
While Loops
carList = Array["Mazda", "Toyota", "Honda"] while carList.length > 0 puts carList[0] carList.shift() end puts carList.length
Loop Breaks
cars = ['Toyota', 'Honda', 'Mazda'] i = 0; for car in cars do if car == "Honda" puts "Found at index #{i}" break else puts "Visited index #{i}" i += 1 end end
Recursion
def getSum(arr) return 0 if arr.empty? firstVal = arr[0]; arr.shift(); return firstVal + getSum(arr); end testArr = Array[1, 2, 4, 5] sum = getSum(testArr) puts sum
Regex Words
phrase = "I am legend" pattern = /[a-zA-Z]+/ result = pattern.match(phrase) puts result;
Regex Numbers
phrase = "I am 23" pattern = /[0-9]+/ result = pattern.match(phrase) puts result;
Regex Test
phrase = "Bob Lee" pattern = "Lee" result = phrase.include? pattern puts result;
Regex Characters
phrase = "##I am legend##" pattern = /\#+\w+/ result = pattern.match(phrase) puts result;