Categories
ruby

Learn Ruby in one video (with source code)

Hi Guys,

A couple of months back I released a vide on “Learn Ruby Programming in 3 hours | FULL COURSE”. Here is the link for that video just in case if you want to check that out :

Also if you want the complete source code for the video. Here is the full code :

puts "Hello to Ruby Programming Language"

#variables, constants and literals  

first_name = 'Alex'
last_name = 'James'

puts first_name 
puts last_name 

# constants 
PIE = 3.14 
radius = 5 
area = PIE * radius * radius
puts area 

puts 123 
puts 1_234
puts -500 
puts 0366 
puts 0xff 
puts 0b1011 

puts 123.45 

# strings 

full_name = first_name + " " + last_name 

puts full_name 

# string interpolation 

puts "The full name is #{full_name}"

age = 12 
puts "The age of the person is #{age}"

# <<
sentence = "A quick brown fox " 
sentence << "jumps over the ";
sentence << "lazy dog"

puts sentence 

# Manipulation of strings 

#gsub (global substitution)

puts sentence.gsub("dog","cat") 
puts sentence 


# split method 

words = sentence.split(' ')
puts words 

code = "abc_123"
puts code.split("_")

# substrings 
greet = "hello world".freeze
puts greet[0..3]

puts greet[-1]

puts greet.upcase()
puts greet.downcase()
puts greet.capitalize() 
puts greet.reverse() 
puts greet.include? 'w'
puts greet.start_with? 'h'
puts greet.end_with? 'd'

# Immutability and Frozen strings 

# greet[0] = ""
# puts greet 
puts greet.frozen?

# object_id 
string_one = "tommy".freeze 
string_two = "tommy".freeze 

puts string_one.object_id == string_two.object_id 

# Arrays in Ruby 

superheroes = ['spider-man','super-man','goku']

puts superheroes[0]
puts superheroes[1]
puts superheroes[2]

# printing first element of the array 
puts superheroes.first 
# printing last element of the array 
puts superheroes.last 

# printing first two elements of the array 
puts superheroes.first(2)
# printing last two elements of the array 
puts superheroes.last(2)

superheroes.push "batman"
puts superheroes 


superheroes << "hulk"
puts superheroes 

last_hero = superheroes.pop 

puts last_hero 
puts superheroes 

superheroes.delete_at(1)

puts superheroes 

# adds an element to the front of the array 
superheroes.unshift "alex"

puts superheroes 

# removing an element from the front of the array 
superheroes.shift 

puts superheroes 

# insert method 

superheroes.insert(2,'power rangers')

puts superheroes 


puts "The size of the array is #{superheroes.size}"
puts "The length of the array is #{superheroes.length}"


numbers =  [1,2,3,4,5]

count = numbers.count { |number| number.even? }

puts "The count of the even numbers in the array is #{count}"

#initialize an array, we can use the square brace 
# notation

# read an element (access) index notation, first, last 

# append an element - push, <<, unshift 
# remove an element - pop, delete_at, shift 

# iterating over an array 

# iterate over the superheroes array 

superheroes.each { |superhero| puts superhero }

# each_with_index 

superheroes.each_with_index { |superhero, index|
puts "superheroes[#{index}] : #{superhero}"}

# each_char and the chars 
some_string = "Alex is a software developer"
some_string.each_char { 
  |character| puts character
}

puts some_string.chars 

# map 

puts superheroes 

superheroes = superheroes.map { |superhero| superhero.upcase() }

puts superheroes 

# select 

# selecting odd numbers 
puts numbers.select { |number| number % 2 == 1}

some_numbers = [1,4,3,2,3.4,5]

some_numbers = some_numbers.sort 

# sorting the numbers in ascending order 
puts some_numbers 

duplicates = [1,3,3,4,5,4,1]

uniques = duplicates.uniq 

puts uniques 

# sample method 

puts numbers.sample 

# take, slice 

first_three = numbers.take(3)
puts first_three 

first_three = numbers[0,3]
puts first_three 

# Splat Operator in Ruby 

*a,b = 1,2,3,4,5 

puts "#{a}, #{b}"

# concat method 
even_numbers = [2,4]
odd_numbers = [1,3]

first_four = even_numbers.concat(odd_numbers)

puts "#{first_four}"

# concat method mutates the original array as well 
# on which it gets applied
puts "#{even_numbers}, #{odd_numbers}"

# & operator  
puts "The common elements are #{even_numbers & odd_numbers}"

# | operator 
puts "The union is #{even_numbers | odd_numbers}"

puts "#{duplicates | some_numbers}"

# HASH TABLES 

# CREATING a hash table 

items = { }

items[:pen] = 2
items[:pencil] = 5
items[:laptop] = 6

puts "The quantity of pens are #{items[:pen]}"
puts "The quantity of the pencils are #{items[:pencil]}"
puts "The quantity of the laptops are #{items[:laptop]}"

# iterate over the hash tables 

# each 

puts "Current items : #{items}"

# print each key-value pair 

items.each do |item, quantity|
  puts "#{item}:#{quantity}"
end 

# each_key, each_value 


items.each_key do |item|
  puts "#{item}"
end 


items.each_value do |quantity|
  puts "#{quantity}"
end 

# keys, values 
puts "#{items.keys}"
puts "#{items.values}"

# key? 

puts "#{items.key?(:pencil)}"
puts "#{items.key?(:tab)}"

# Exercise: 
given_string = "thenerdydev" 

frequency_ht = { } # initialization 

# iterate over the given string 

given_string.each_char do |character|
  if frequency_ht.key?(character)
    frequency_ht[character] += 1
  else
    frequency_ht[character] = 1
  end 
end 

puts "#{frequency_ht}"

# Exercise:
frequency_ht.each do |k,v|
  if v == 1
    puts k 
  end 
end 

# fetch and merge methods 

hash_table = { } 

puts "#{hash_table[:something_random]}"

# fetch method 

puts "#{hash_table.fetch(:something_random, 'INVALID')}"


# merging two hash tables 

# merge 

user = { 
  name: 'alex',
  age: 21,
  profession: 'developer'
}

new_user = user.merge({age: 41, country: 'UK'})

puts "Original hash table : #{user}"
puts "New hash table : #{new_user}"

#dig method 

person = {
  details: { 
    name: 'alex',
    gender: 'male',
    profession: 'developer',
    age: 21
  }
}

puts person.fetch(:details).fetch(:name)

puts person.dig(:details, :name)

puts person.dig(:details, :anything)

# transform_values 

puts items 

items = items.transform_values { |v| v*2}

puts items 

# Sets 

require 'set' 

numbers = Set.new 

numbers << 1 
numbers << 2 
numbers << 3 
numbers << 2 

puts "#{numbers}"

puts numbers.include?(1)

# ranges 

puts "#{('a'..'z').to_a}"

# numbers ranging from 1 to 10 

puts "#{(1..10).to_a}"

# step method 

puts "#{(1..10).step(2).to_a}"
# iterate over a range of numbers from 1 to 10 

(1..10).each {|number| puts number }

# random number in range(1,10)

random_number = rand(1..10)
puts "The random number is #{random_number}"

# Data Serialization 

# csv and json 


# CSV (comma separated values )

require 'csv'

puts CSV.read('items.csv', headers: true)


# json 

require 'json'

json_object = '{
  "pen" : 300,
  "pencil": 400,
  "laptop": 600
}'
hash = JSON.parse(json_object)

puts hash 

puts hash.to_json 


# all classes in Ruby inherit from the Object class 
# Object < BasicObject 

puts json_object.class 
puts hash.class 


# methods 

def greet()
 puts "Good morning!"
end 

greet()

def add(number_one, number_two)
  return number_one + number_two 
end 

result = add(2,3)
puts "The addition of 2 and 3 gives #{result}"

# Class 

puts Array.class
puts String.class 
puts Hash.class 
puts Integer.class 

class Customer
  attr_reader :id, :name, :age, :type, :gender
  attr_accessor :type 
  @@customer_count = 0 

  def self.count
    @@customer_count
  end 

  def initialize(id, name, age, type, gender)
    @id = id 
    @name = name 
    @age = age 
    @type = type 
    @gender = gender 
    @@customer_count += 1 
  end 
  
  def display_customer_details()
    puts "Customer id: #@id"
    puts "Customer name: #@name"
    puts "Customer age: #@age"
    puts "Customer type: #@type"
    puts "Customer gender: #@gender"
  end 
end 

puts "Current count of customers : #{Customer.count}"
customer_one = Customer.new(1, 'alex', 21, 'high-spender', 'male')
customer_two = Customer.new(2, 'james',29,'low-spender','male')
puts "Current count of customers after creation : #{Customer.count}"

# call methods 
customer_one.display_customer_details()
customer_two.display_customer_details()

puts customer_one.id 
puts customer_one.name 
puts customer_one.age 
puts customer_one.gender 

# attr_writer, attr_accessor
customer_two.type = 'high-spender'
puts customer_two.display_customer_details()


# public access control, private access control 
# protected access control 

# private methods 

# protected methods 

class Cube
  def initialize(side)
    @side = side 
  end 

  def getArea()
    return 6 * @side * @side 
  end 

  def getVolume()
    return @side * @side * @side 
  end 

  private :getArea, :getVolume 

  def printArea()
    area = getArea()
    puts "The area of the cube is #{area}"
  end 

  def printVolume()
    volume = getVolume()
    puts "The volume of the cube is #{volume}"
  end 
end 

# instantiation 
cube_one = Cube.new(4)
cube_one.printArea()
cube_one.printVolume() 

# Inheritance in RUby 

class A
  def doSomething()
    puts "Doing something..."
  end
  def walkTheDog()
    puts "Walking with the dog..."
  end 
end 

class B < A
  def doThat()
    puts "Doing that..."
  end 
  def singSong()
    puts "Singing the song.."
  end 
end 

b = B.new 
puts b.doSomething()
puts b.walkTheDog() 
puts b.doThat() 


# Ruby blocks 
[1,2,3].each { |number| puts number} 

# multiline block 

[1,2,3].each do |number| 
  puts number
end 

# yield keyword in ruby 

def a()
  puts "inside a"
  yield 
  puts "coming out of a"
end 

a { puts "hello from outside of a" }

def perform_operation()
  yield 2*3
  puts "inside perform_operation"
  yield 5/6 
end 


perform_operation { |number| puts "#{number}" }

def print_2_times()
  yield 
  yield 
end 

print_2_times { puts "Hello World "}

# Lambda 

first = -> { puts "This is a lambda"}

first.call 
first.call() 
first.() 
first[]
first.=== 

multiply_by_2 = ->(num) { num * 2 }

puts multiply_by_2.call(4)

# Procs in Ruby 

result = Proc.new do |a,b|
  puts "inside the proc"
  sum = a + b 
  product = a * b 
  puts "The sum of #{a} and #{b} is #{sum}"
  puts "The product of #{a} and #{b} is #{product}"
  puts "coming out of the proc"
end

result.call(2,4)

puts Proc.instance_methods

b = Proc.new { |one, two| puts "#{one}, #{two}"}

b.call 

b = ->(one, two) { puts "#{one}, #{two}"}

b.call(2,3)

# lambda 
hello = -> { return 'hello'}

puts "#{hello.call}"

#  proc 
# hello = Proc.new { return 'hello'}
# puts "#{hello.call}"

def hello_method()
  puts "before proc execution..."
  hello = Proc.new { return 'hello'}
  puts "#{hello.call}"
  puts "after proc execution..."
end 

hello_method() 

# procs and lambdas 
# Proc.new {} , ->() {} 
# returns from the current method, return from the lambda 
# procs do not care about arguments while lambdas 
# raise an exception in such cases

# Closures 

def invoke_proc(proc_fn)
  counter = 1
  proc_fn.call 
end 

counter = 0
proc_fn = Proc.new { puts counter }

invoke_proc(proc_fn)

# binding class 

def get_binding()
  foo = 1 
  bar = 2 
  binding 
end 

puts get_binding.eval('foo')
puts get_binding.eval('bar')

# puts foo 
# puts bar

string_one = "I love JavaScript and Ruby"

puts string_one =~ /love/ 

puts string_one.include? 'love' 

# Character classes 

# [aeiou]

def includes_vowel(string_one)
  return string_one =~ /[aeiou]/
end 

puts includes_vowel('love')
puts includes_vowel('nerd')
puts includes_vowel('xyz')

#character ranges 

puts /[1-4]/

def contains_number_from_14(number_one)
  return number_one =~ /[1-4]/
end 

puts contains_number_from_14('23456')
puts contains_number_from_14('7890')

# [0-9],[a-z],[^a-z]
# \d 

#wildcards 

puts "7f4".match(/\d.\d/)
puts "7f4".match(/\d\.\d/)
puts "7.4".match(/\d\.\d/)

# Modifiers 

# +  one or more characters 
# *  zero or more characters 
# ?  zero or one character 
# {2,4}, {5,9}

def validate_ip_address(string_one)
  return !!(string_one =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)
end 

puts validate_ip_address("176.334.1.1")
puts validate_ip_address("000.334.1.1")
puts validate_ip_address("0000.334.1.1")

# ^

puts !!"the nerdy dev".match(/^the/)

# Modules 

module Computation
  PIE = 3.14
  def self.double(number)
    return number*2
  end 
end 

puts Computation::PIE
puts Computation.double(45)

# include 

class Calculator 
  include Computation
end 

puts Calculator.ancestors 


module Al

end 

class B 
end 

class C < B
  include Al 
end 

puts C.ancestors 

# Enumerable 

# inject 

result = [1,2,3,4,5].inject { |acc, current_number| acc + current_number }

puts "#{result}"


items_count = { }
items_count[:pencils] = 20 
items_count[:pens] = 45
items_count[:laptops] = 3 

puts "Current hash map : #{items_count}"

count_of_items = items_count.inject(0) { 
 |acc, (key, value) | acc + value
}

puts "Count of items : #{count_of_items}"

# class ProductRepository extend Enumerable
#   def self.all
#     [
#     Product.new('A Perfume', 24),
#     Product.new('A Shoe', 67),
#     Product.new('Apple Macbook', 3000)
#   ]
#   end 

#   def self.each
#     all.each {|product| yield product } 
#   end 
# end 


# Product = Struct.new(:product_name, :product_price)

# puts ProductRepository.select {
#   |product| product.product_price > 90
# }

# implement map method 

class Shop
  attr_accessor :products 

  def initialize
      @products = [
      Product.new('A Perfume', 24),
      Product.new('A Shoe', 67),
      Product.new('Apple Macbook', 3000)
    ]
  end
  def map()
    results = []
    @products.each { |product| results << yield(product)}
    return results 
  end 
end 

Product = Struct.new(:product_name, :product_price)



# instance for shop 
shop = Shop.new 
puts "#{shop.map(&:product_name)}"

# enumerator objects

puts "#{[1,2,3,4].to_enum()}"

enum = [1,2,3,4].select 
puts enum.class 

puts enum.each { |number| number % 2 == 0}

# next 
puts enum.next 
puts enum.next 
puts enum.next 
puts enum.next 
# puts enum.next 

enum.rewind 
puts enum.next 
enum.rewind 

loop {
  puts enum.next 
}

# Exceptions 

# def buy_cheese()
#   puts "cheese bought!"
# end 


# def buy_chocolate()
#   raise "No chocolate left!"
# end 


# def go_shopping()
#   buy_cheese() 
#   buy_chocolate() 
# end 


# go_shopping() 

# 1.txt 

# File.open("1.txt")

def open_file() 
  content = File.read("items.csv")
  File.write('items-copy.csv', content)
rescue Errno::ENOENT => ex
  puts "File not found.."
  puts ex.message 
  puts ex.backtrace 
end 


open_file()

# ensure 

begin 
  puts "Inside the begin block"
ensure 
  puts "I will always get executed"
end 


# map and all 

array_elements = Array(1..10_00_000)
array_elements.lazy.map {|n| puts n; n ** 2 }.all? {
  |n| n < 500; 
}

I hope you enjoyed the video. Do like, share and subscribe to my channel for more such awesome videos. Keep coding !

Leave a Reply

Your email address will not be published.