Ruby Basic

Muhammad Tri Wibowo
5 min readNov 20, 2023

--

Hello world

puts "Hello World"

Method

def mymethod
puts "mymethod running"
end

def mymethodparam(param1,param2)
puts "param1 : #{param1}, param2 : #{param2}"
end

mymethod
mymethodparam "hello", "world"

String

#String concat structure:
=begin
String1 + String2
String1 + " " + String2 + String3
=end

param1 = "hello"
param2 = "world"
param3 = param1+" "+param2

puts param3

String — method

objectname.nil?

objectname.empty?

objectname.length

objectname.reverse

name = "Mashrur"

puts "My name is #{name}"

String — from input

#To get input from the command line use the following method:
#gets.chomp

var1 = gets.chomp
puts var1

Numbers

puts 1 + 2

=begin
Different operations:
1 + 2
1 * 2
1 / 2
1 - 2
1 % 2
=end

#20 is an integer, 20.0 is a float
#or

20.to_f

#Methods you can use:

object.odd?

22.odd?

object.even?

22.even?

#Comparisons:

a == b

1 == 2

3 == 3

5 < 2

2 <= 5

5 > 2

5 && 6

5 || 6

#Generate a random number between 0 and less than 10:

rand(10)

#To convert an string object to integer:
#objectname.to_i

"5".to_i

#To convert an object to string:
#objectname.to_s

5.to_s

Method and If/else/branching

def multiply(first_number, second_number)
first_number.to_f * second_number.to_f
end

def divide(first_number, second_number)
first_number.to_f / second_number.to_f
end

def subtract(first_number, second_number)
second_number.to_f - first_number.to_f
end

def mod(first_number, second_number)
first_number.to_f % second_number.to_f
end

puts "What do you want to do? 1) multiply 2) divide 3) subtract 4) find remainder"
prompt = gets.chomp
puts "Enter in your first number"
first_number = gets.chomp
puts "Enter in your second number"
second_number = gets.chomp
if prompt == '1'
puts "You have chosen to multiply #{first_number} with #{second_number}"
result = multiply(first_number, second_number)
elsif prompt == '2'
puts "You have chosen to divide"
result = divide(first_number, second_number)
elsif prompt == '3'
puts "You have chosen to subtract"
result = subtract(first_number, second_number)
elsif prompt == '4'
puts "You have chosen to find the remainder"
result = mod(first_number, second_number)
else
puts "You have made an invalid choice"
end

Array

#Array, created by including elements within square brackets:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#The index for an array starts with 0, so in the array above a[0] is 1
#Some methods you can use on arrays:

arrayname.empty?

arrayname.include?(itemname)

arrayname.reverse

arrayname.reverse! # use ! at the end to change the original array

arrayname.shuffle

arrayname.push(30) # will append new element 30 to the end array

arrayname << 25 # << known as shovel operator will also append new element to the end of the array

arrayname.unshift("someelement") # will add element "some element" to the beginning of the array

arrayname.pop # will remove the last element of the array and return 1

arrayname.uniq # will remove all the duplicates and display (will not change the original array)

arrayname.uniq! # will remove all the duplicates in the original array

#A range:

(0..25).to_a

#will create an array with elements from value 0 to 25

(0..99).to_a.shuffle!

#will create an array with elements from value 0 to 99 in random order
#To loop through an array named y using the .each method and print out the value of each element:

y.each { |i| puts i }

#In plain terms: For each element i in array y print the value of i
#To execute iteration through an array called names using a block:

names.each do |randomvariablename| # starts the do block

puts "Hello #{randomvariablename}" # executes code for each element

end # ends the do block

#To capitalize (or use another method) on each element of array called names:

names.each { |randomvariablename| puts "Hello #{randomvariablename.capitalize}" }

#Using the select method to pickup all the odd numbers from an array y:

y.select { |number| number.odd? } # selects the value and returns it only if the condition is met

#To join the elements of an array named p:

p.join

#To join the elements of an array with space in between each element:

p.join(" ")

#To join the elements of an array with dash in between each element:

p.join("-")

Hash / Dictionary / Map

#To create a hash called my_details include the elements within { }:

my_details = {'name' => 'mashrur', 'favcolor' => 'red'}

#To access the value and notify me what favcolor is:

my_details["favcolor"]

#Alternate syntax to create key, value pairs in hash:

myhash = {a: 1, b: 2, c: 3, d: 4}

#But this will create symbols a, b, c and d (not strings) as keys
#To access the value for key c above:

myhash[:c]

#To add a key, value pair to the hash above:

myhash[:d] = 7

myhash[:name] = "Mashrur"

#To delete a key, value pair simply delete the key:

myhash.delete(:d)

#To list the keys in a hash, followed by values of the hash:

myhash.keys
myhash.values

#To iterate through a hash using .each method and print out value:

myhash.each { |somekey, somevalue| puts somevalue }

#To iterate through a hash using .each method and print out both key and value in friendly format:

myhash.each { |somekey, somevalue| puts "The key is #{somekey} and the value is #{somevalue}" }

#To iterate through and delete a items from a hash based on a condition (in the condition below if the value is greater than 3:

myhash.each { |k, v| myhash.delete(k) if v > 3 }

#Use select method to display items only if value of the item is odd

myhash.select { |k, v| v.odd? }

Snake Case

def method_name
# write code here
end

this_is_snake_case.rb

Class

class Student
attr_accessor :first_name, :last_name, :email, :username, :password

def initialize(firstname, lastname, username, email, password)
@first_name = firstname
@last_name = lastname
@username = username
@email = email
@password = password
end

def to_s
"First name: #{@first_name}, Last name: #{@last_name}, Username: #{@username},
email address: #{@email}"
end

end

mashrur = Student.new("Mashrur", "Hossain", "mashrur1", "mashrur@example.com",
"password1")
john = Student.new("John", "Doe", "john1", "john1@example.com",
"password2")
puts mashrur
puts john
mashrur.last_name = john.last_name
puts "Mashrur is altered"
puts mashrur

Bcrypt

require 'bcrypt'

class User < ActiveRecord::Base
# users.password_hash in the database is a :string
include BCrypt

def password
@password ||= Password.new(password_hash)
end

def password=(new_password)
@password = Password.create(new_password)
self.password_hash = @password
end
end

require 'bcrypt'

my_password = BCrypt::Password.create("my password")
#=> "$2a$12$K0ByB.6YI2/OYrB4fQOYLe6Tv0datUVf6VZ/2Jzwm879BW5K1cHey"

my_password.version #=> "2a"
my_password.cost #=> 12
my_password == "my password" #=> true
my_password == "not my password" #=> false

my_password = BCrypt::Password.new("$2a$12$K0ByB.6YI2/OYrB4fQOYLe6Tv0datUVf6VZ/2Jzwm879BW5K1cHey")
my_password == "my password" #=> true
my_password == "not my password" #=> false
require 'bundler/inline'

gemfile true do
source 'http://rubygems.org'
gem 'bcrypt'
end

require 'bcrypt'

users = [
{ username: "mashrur", password: "password1" },
{ username: "jack", password: "password2" },
{ username: "arya", password: "password3" },
{ username: "jonshow", password: "password4" },
{ username: "heisenberg", password: "password5" }
]

def create_hash_digest(password)
BCrypt::Password.create(password)
end

def verify_hash_digest(password)
BCrypt::Password.new(password)
end

def create_secure_users(list_of_users)
list_of_users.each do |user_record|
user_record[:password] = create_hash_digest(user_record[:password])
end
list_of_users
end
require 'bundler/inline'

gemfile true do
source 'http://rubygems.org'
gem 'bcrypt'
end

module Crud
require 'bcrypt'
puts "Module CRUD activated"

def Crud.create_hash_digest(password)
BCrypt::Password.create(password)
end

def Crud.verify_hash_digest(password)
BCrypt::Password.new(password)
end

def Crud.create_secure_users(list_of_users)
list_of_users.each do |user_record|
user_record[:password] = create_hash_digest(user_record[:password])
end
list_of_users
end

def Crud.authenticate_user(username, password, list_of_users)
list_of_users.each do |user_record|
if user_record[:username] == username && verify_hash_digest(user_record[:password]) == password
return user_record
end
end
"Credentials were not correct"
end
end

Inheritence

class Box
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# instance method
def getArea
@width * @height
end
end

# define a subclass
class BigBox < Box

# add a new instance method
def printArea
@area = @width * @height
puts "Big box area is : #@area"
end
end

# create an object
box = BigBox.new(10, 20)

# print the area
box.printArea()

https://www.tutorialspoint.com/ruby/ruby_object_oriented.htm

--

--