[Rails] Ruby Basics

Tags
Rails
Engineering
Created
Oct 12, 2023 03:47 AM
Edited
Oct 11, 2023
Description
Language syntax + block/module + require/include

Everything is an object

10.class
# Integer

"ruby".methods
# [
#   ...
# ]

Variable

  1. local: within a scope
  1. instance: @, in Rails, conventionally accessible in views
  1. class: @@
  1. global: $, accessible everywhere

Symbol

puts "string".object_id  
puts "string".object_id  
puts :symbol.object_id  
puts :symbol.object_id

# 21066960  
# 21066930  
# 132178  
# 132178

Hash

Just like dict in Python
colors = { 
	"red" => 0xf00, 
	"green" => 0x0f0, 
	"blue" => 0x00f 
}

H = Hash["a" => 100, "b" => 200]

Array

nums = Array.new(10) { |e| e = e * 2 }
puts "#{nums}"

# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# all works
nums = Array.[](1, 2, 3, 4, 5)
nums = Array[1, 2, 3, 4, 5]
nums = Array(1..5)

Range

A range (1..5) means it includes 1, 2, 3, 4, 5 values and a range (1...5) means it includes 1, 2, 3, 4 values.
(10..15).each do |n| 
   print n, ' ' 
end

# 10, 11, 12, 13, 14, 15

If else statement

if a
	puts a
elsif b
	puts b
else
	puts c
end

Unless

  • execute code if the statement is false
    • if something → unless !something
    • unless = if not
  • Better not use this if the condition is complicated or has lots of || or &&
unless x>=2
   puts "x is less than 2"
 else
   puts "x is greater than 2"
end

Case

case expr0
	when expr1, expr2
	   stmt1
	when expr3, expr4
	   stmt2
	else
	   stmt3
end

While loop

while True do
	puts "infinite loop"
end
The block will at least executed once in the code below.
begin
	puts "infinite loop"
end while True
Execute code if the condition is false.
until False do
	puts "infinite loop"
end
At least execute once inside the block
begin
	puts "infinite loop"
end unitl False

For loop

for i in 1..5
	print i
end

# 1 2 3 4 5
(0..5).each do |i|
   print i
end

# 1 2 3 4 5
  • break
  • next (continue in Python)
  • redo: restart the most internal loop from the first iteration
  • retry: restart from the begin body or the loop

Class Constructor

class Object
	def initialize(param1)
		@param1 = param1
	end
end

object = Object.new(myParam1)

Class Method

class Object
	def Object.foo
		puts "this is a class method"
	end
end

Object.foo
# this is a class method

Return values from method

By default, alway return the last value in the method.
def method
	returned_value = 0
end

Variable number of parameters

def method(*params)
	for i in 0...params.length
		param = params[i]
	end
end

Block

block_name {
   statement1
   statement2
   ..........
}

yield

Kind of like a saving point.
def test
   puts "You are in the method"
   yield
   puts "You are again back to the method"
   yield
end
test {puts "You are in the block"}

# You are in the method
# You are in the block
# You are again back to the method
# You are in the block

Pass parameters with yield

def test
   yield 5
   puts "You are in the method test"
   yield 100
end
test {|i| puts "You are in the block #{i}"}

# You are in the block 5
# You are in the method test
# You are in the block 100

Pass a block into method and call it

def test(&block)
   block.call
end
test { puts "Hello World!"}

# Hello World!

BEGIN and END blocks

BEGIN { 
   # BEGIN block code 
   puts "BEGIN code block"
} 

END { 
   # END block code 
   puts "END code block"
}
   # MAIN block code 
puts "MAIN code block"

# BEGIN code block
# MAIN code block
# END block block

Module

To put classes, methods, and constants together
module Moral
   VERY_BAD = 0
   BAD = 1
   def Moral.sin(badness)
   # ...
   end
end
💡
You can put things in a module in different files for multiple times! For example, in another file, you can have a module Moral too!

require and include

require is just like include or import in other languages
require 'pp'
include is to embed a module in a class
module Week
   FIRST_DAY = "Sunday"
   def Week.weeks_in_month
      puts "You have four weeks in a month"
   end
   def Week.weeks_in_year
      puts "You have 52 weeks in a year"
   end
end


class Decade
include Week
   no_of_yrs = 10
   def no_of_months
      puts Week::FIRST_DAY
      number = 10*12
      puts number
   end
end
d1 = Decade.new
puts Week::FIRST_DAY
Week.weeks_in_month
Week.weeks_in_year
d1.no_of_months

# Sunday
# You have four weeks in a month
# You have 52 weeks in a year
# Sunday
# 120
💡
:: is used to access an object from a module, ex: a variable, a class.

Mixins

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