Quickest Ruby Tutorial

Divyanshu Negi

🚀🚀🚀 5 min read

I am working on a fastlane file and it contains Ruby code, I want to optimise the code and functions used in that file so thought why not learn some basics of Ruby programming language, here is what I learned

  • Ruby is Object oriented programming language, good news for you Kotlin, Java, Swift devs
  • Ruby development focus was on programmer and not the machine so the developer wanted it to be fun and easy to use, will see about that in a while.
  • All Ruby code is run using an interpreter, but there are some implementation of Ruby where we can compile the code and run on VMs.
  • Most famous Ruby interpreter is called MRI (Matz's Ruby Interpreter)
  • Ruby has a Garbage collector
  • Ruby became most popular due to the Ruby on Rails web application development framework. which is being used by large companies like, Github, twitch, Hulu, etc.

This would be the file name of a ruby app.

App.rb

To run the ruby file simply go to terminal and enter this command

ruby your_file_name.rb

(If Ruby is not installed in the system first install that, would be much simpler to use something like brew on a mac)

Here we print a simple "Hello World!"

#Printing

puts "Hello"
print "World"
puts "!"

puts simply prints and enter a new line as well, whereas print will only print in the same line.

  • variable names are case sensitive, standard is start with a lower case word, additional word separated by _ ex. this_is_variable

name = "Honey"     # String
age = 30         # Integer
temp = 24.5      # Decimal
is_coding = true # Boolean

name = "Div"

puts "Your name is #{name}"
# or
puts "Your name is " + name

casting of data types


puts 3.14.to_i # To Integer
puts 3.to_f.   # To FLoat   
puts 3.0.to_s # To String


puts 100 + "50".to_i # To Integer and add a number
puts 100 + "50.99".to_f # To FLoat and add to a number

How to play with String


greeting = "Hello"
#indexes:   01234

puts greeting.length
puts greeting[0]
puts greeting.include? "llo"
puts greeting.include? "z"
puts greeting[1,3] #ell

how to play with numbers


puts 2 * 3     # Basic Arithmatic: +,-,/,*
puts 2 ** 3    # Exponent
puts 10 % 3    # Module Op, : returns remainder of 10/3
puts 1 + 2 * 3 # order of operations
puts 10 / 3.0  # int's and doubles

num = 10
num += 100 # +=, -=, /= , *=
puts num # 110

num -36.8
puts num.abs()
puts num.round()

# usefull Math class API
puts Math.sqrt(144)
puts Math.log(0)

Getting user inputs ?


puts "Enter your name: "
name = gets # better to use gets.chomp , which will not take the new line when press enter
puts "Hello #{name}, how are you ?"

# Example 2

puts "Enter first num:"
num_one = gets.chomp
puts "Enter second num:"
num_two = gets.chomp
puts num_one.to_f + num_two.to_f

gets wait for a user input in the terminal, gets.chomp only takes and string entered and ignores the new line when enter is pressed after input.

Arrays in Ruby


numbers = [4, 8, "wow", 16, 34]
# can have multiple data types in an array

numbers[0] = 90
puts numbers[0] # prints 90
puts numbers[1] # prints 8
puts numbers[-1] # prints 34, as last number from array

puts numbers[2,3] # first is the index argument, second the range, so prints wow,16,34
puts numbers[2..4] # prints the range from 2 to 4 as wow,16,34

puts numbers.length # prints the length of array
# Array methods

friends = []
friends.push("Oscar")
friends.push("Kevin")
friends.push("Taras")

friends.pop # would pop the last element from the array

friends.reverse # reverse the elements in the array
friends.sort # sorts the array , would not work with multiple data types in an array, will sort but with wierd results

friends.include? "kevin" # will return if string exists or not in array

Functions or Methods

def add_numbers(num1,num2=99)
	return num1 + num2
end

# we define the function with a def keyword, followed by name, and params, we can set param value as default, to close the function scope we need to set an end 

sum = add_number(4)
puts sum # prints 4 + 99 = 103

Conditionals

is_student = false
is_smart = true

if is_student and is_smart
 puts "You are a student"
elseif is_student and !is_smart
 puts "You are not a smart student"
else 
 puts "You are not a student"
end

# >,<, >= , <=, !=, == , String.equals()
if 1 > 3
	puts "number comparission was true"
end

if "a" > "b"
	puts "string comparison was true"
end

Switch Statements

my_grade = "A"

case my_gradde
	when "A"
		puts "You pass"
	when "F"
		puts "You fail"
	else 
		puts "Invalid Grade"		
end		

Dictionaries or Associated Arrays, can store key value pairs

  • Dictionaries do not have a indexing, so numbers will be part of the keys

# Keys has to be Unique
test_grades = {
	"Andy" => "B+",
	:Stanley => "C", # can also define in this format if do not want to use the stirng quotes
	"Ryan" => "A",
	3 => 95.2,
}

test_grades["Andy"] = "B-"

puts test_grades["Andy"]
puts test_grades[:Stanley]
puts test_grades[3]

While and For loops

# While loop

index = 1
while index <= 5
	puts index
	index += 1
end
# For loop

for index in 0..5
	puts index
end

5.times do |index|
	puts index
end

numbers = [4,5,6,3,4,6]

for num in numbers
	puts num
end

numbers.each do |num|
	puts num
end

Exception catching in Ruby


num = 10/0 

begin
	num = 10/0
rescue # will catch any error
	puts "Error"
end

# specific error catching

begin 
	num = 10/0
rescue ZeroDivisionError
	puts "Error"
rescue 
	puts "All other error"
end

raise "Made up exception"

OOPs in Ruby

  • Everything in Ruby is an object, similar to JS
  • attr_accessor will define the attributes for the class
  • can simple add functions inside the class
  • also self would be like this will be in the scope of the class object
class Book
	attr_accessor :title, :author 
	def readBook()
		puts "Reading #{self.title} by #{self.author}"
	end
end

book1 = Book.new()
book1. title = "Harry Potter"
book1.author = "JK Rowling"

book1.readBook()
puts book1.title

constructors in ruby classes

class Book
	attr_accessor :title :author
	def initialize(title, author)
		@title = title
		@author = author
	end

	def readBook()
		puts "Reading #{self.title} by #{@author}"
	end

end

book1 = Book.new("Harry Potter", "JK Rowling")
# book1.title = "some new title"

Getters and Setters


class Book
	attr_accessor :title :author
	def initialize(title, author)
		self.title = title
		@author = author
	end

	def title=(title)
		puts "Set"
		@title = title
		
	def title
		puts "Get"
		return @title
		
	def readBook()
		puts "Reading #{self.title} by #{@author}"
	end

end

book1 = Book.new("Harry Potter", "JK Rowling")
# book1.title = "some new title"

Inheritance


class Chef
	def make_chicken()
		puts "Making chicken"
	end
	
	def make_salad()
		puts "Making Salad"
	end
end

class ItalianChef < Chef # using this < sign makes the inheritance possible
	def make_pasta()
		puts "Making Pasta"
	end
end

chef = Chef.new()
chef.make_chicken()

italian_chef = ItalianChef.new()
italian_chef.make_chicken()
italian_chef.make_pasta()

How to Import ruby files ?

here in the example, it will look into a folder named test for a file named file_name.rb to import.

require_relative "test/file_name"

I had so much fun learning this language, and going to clean my fastfiles which have now 500+ lines of duplicated code, the OOP concepts will help me clean it and make better automations to deploy our mobile apps.

Thanks for reading 🙏

X

Did this post help you ?

I'd appreciate your feedback so I can make my blog posts more helpful. Did this post help you learn something or fix an issue you were having?

Yes

No

X

If you'd like to support this blog by buying me a coffee I'd really appreciate it!

X

Subscribe to my newsletter

Join 107+ other developers and get free, weekly updates and code insights directly to your inbox.

  • No Spam
  • Unsubscribe whenever
  • Email Address

    Powered by Buttondown

    Picture of Divyanshu Negi

    Divyanshu Negi is a VP of Engineering at Zaapi Pte.

    X