Introduction to Ruby and Rails
Introduction to Ruby and Rails
END
{
puts "END of the program"
}
BEGIN
{
puts "BEGINNING of the Program"
} Output:
BEGINNING of the Program
This is main body of program
What is scalar in Ruby?
• The scalar() is an inbuilt method in Ruby
returns an N x N diagonal matrix where
each diagonal element is value.
• Scalars are “leaf” values in GraphQL.
• There are several built-in scalars, and you
can define custom scalars, too.
• Enums are also leaf values.
• The built-in scalars are:
Scalar Types in Ruby
• String, like a JSON or Ruby string
• Int, like a JSON or Ruby integer
• Float, like a JSON or Ruby floating point decimal
• Boolean, like a JSON or Ruby boolean (true or false)
• ID, which a specialized String for representing unique object
identifiers
• ISO8601DateTime, an ISO 8601-encoded datetime
• ISO8601Date, an ISO 8601-encoded date
• JSON, ⚠ This returns arbitrary JSON (Ruby hashes, arrays,
strings, integers, floats, booleans and nils). Take care: by
using this type, you completely lose all GraphQL type safety.
Consider building object types for your data instead.
• BigInt, a numeric value which may exceed the size of a 32-
Fields can return built-in scalars by referencing by name:
# String field:
field :name, String,
# Integer field:
field :top_score, Int, null: false
# or:
field :top_score, Integer, null: false
# Float field
field :avg_points_per_game, Float, null: false
# Boolean field
field :is_top_ranked, Boolean, null: false
# ID field
field :id, ID, null: false
# ISO8601DateTime field
field :created_at, GraphQL::Types::ISO8601DateTime, null: false
# ISO8601Date field
field :birthday, GraphQL::Types::ISO8601Date, null: false
# JSON field ⚠
field :parameters, GraphQL::Types::JSON, null: false
# BigInt field
• Custom scalars can also be used by name:
# `homepage: Url`
field :homepage, Types::Url
• In the Schema Definition Language (SDL), scalars are
simply named:
• scalar DateTime
• Custom Scalars
• You can implement your own scalars by extending
GraphQL::Schema::Scalar.
• Your class must define two class methods:
• self.coerce_input takes a GraphQL input and converts it
into a Ruby value
• self.coerce_result takes the return value of a field and
prepares it for the GraphQL response JSON
# app/graphql/types/base_scalar.rb
# Make a base class:
class Types::BaseScalar < GraphQL::Schema::Scalar
end
# app/graphql/types/url.rb
class Types::Url < Types::BaseScalar
description "A valid URL, transported as a string"
def self.coerce_input(input_value, context)
# Parse the incoming object into a `URI`
url = URI.parse(input_value)
if url.is_a?(URI::HTTP) || url.is_a?(URI::HTTPS)
# It's valid, return the URI object
url
else
raise GraphQL::CoercionError, "#{input_value.inspect} is not a valid URL"
end
end
def self.coerce_result(ruby_value, context)
# It's transported as a string, so stringify it
ruby_value.to_s
Ruby Variables
• Ruby variables are locations which hold data to be used
in the programs.
• Each variable has a different name. These variable names
are based on some naming conventions.
• Unlike other programming languages, there is no need to
declare a variable in Ruby.
• A prefix is needed to indicate it.
• There are four types of variables in Ruby:
• Local variables
• Class variables
• Instance variables
• Global variables
• Each variable in Ruby is declared by using a special
character at the start of the variable name which is
mentioned in the following table:
@ Instance Variable
@@ Class Variable
$ Global Variable
Local Variables
• A local variable name always starts with a lowercase
letter(a-z) or underscore (_).
• These variables are local to the code construct in which
they are declared.
• A local variable is only accessible within the block of its
initialization.
• Local variables are not available outside the method.
There is no need to initialize the local variables.
• Example:
age = 10
_Age = 20
Instance Variables
• Here variable name always starts with a @ sign.
• They are similar to Class variables but their values are
local to specific instances of an object.
• Instance variables are available across methods for any
specified instance or object i.e. instance variables can
change from object to object.
• There is no need to initialize the instance variables and
uninitialized instance variable always contains a nil
value.
• Instance Variables
@cust_id = id
@cust_name = name
@cust_addr = addr
Class Variables
• A class variable name always starts with @@ sign.
• It is available across different objects.
• A class variable belongs to the class and it is a
characteristic of a class.
• They need to be initialized before use.
• Another way of thinking about class variables is as
global variables within the context of a single class.
• A class variable is shared by all the descendants of the
class.
• An uninitialized class variable will result in an error.
• # class variable
@@no_of_customers = 0
Example: How to create class using Ruby
#!/usr/bin/ruby
# Ruby program to illustrate
# the Class Variables
class Customer
# class variable
@@no_of_customers = 0
def initialize(id, name, addr)
# An instance Variable
@cust_id = id
@cust_name = name
@cust_addr = addr
end
# displaying result
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
def total_no_of_customers()
# class variable
@@no_of_customers += 1
puts "Total number of customers: #@@no_of_customers"
end
end
# Create Objects
cust1 = Customer.new("1", "John", "Wisdom Apartments,
Ludhiya")
cust2 = Customer.new("2", "Poul", "New Empire road,
Khandala")
# Call Methods
cust1.display_details()
cust1.total_no_of_customers()
cust2.display_details()
cust2.total_no_of_customers()
Output:
Customer id 1
Customer name John
Customer address Wisdom Apartments,
Ludhiya
Total number of customers: 1
Customer id 2
Customer name Poul
Customer address New Empire road,
Khandala
Total number of customers: 2
Global Variables
• A global variable name always starts with $.
• Class variables are not available across classes.
• If you want to have a single variable, which is available
across classes, you need to define a global variable.
• Its scope is global, means it can be accessed from
anywhere in a program.
• By default, an uninitialized global variable has a nil value
and its use can cause the programs to be cryptic and
complex.
• Example:
$global_variable = 10
Ruby Data Types
• Data types in Ruby represents different types of
data like text, string, numbers, etc.
• All data types are based on classes because it is a
pure Object-Oriented language.
• There are different data types in Ruby as
• Numbers
• Boolean
• Strings
• Hashes
• Arrays
• Symbols
Numbers
• Generally a number is defined as a series of
digits, using a dot as a decimal mark.
• Optionally the user can use the underscore as a
separator.
• There are different kinds of numbers like integers
and float.
• Ruby can handle both Integers and floating point
numbers.
• According to their size, there are two types of
integers, one is Bignum and second is Fixnum.
Example:
# Ruby program to illustrate the
# Numbers Data Type
# float type
distance = 0.1
# both integer and float type
time = 9.87 / 3600
speed = distance / time
puts "The average speed of a sprinter is
#{speed} km/h"
Output: The average speed of a sprinter is
36.474164133738604 km/h
• Boolean: Boolean data type represents only one bit of information
either true or false.
• Example:
# Ruby program to illustrate the
# Boolean Data Types
if true
puts "It is True!"
else Output:
puts "It is False!" It is True!
end
if nil nil is False!
puts "nil is True!" 0 is True!
else
puts "nil is False!"
end
if 0
puts "0 is True!"
else
puts "0 is False!"
Strings
• A string is a group of letters that represent a
sentence or a word. Strings are defined by
enclosing a text within a single (”) or double (“”)
quotes.
• You can use both double quotes and single
quotes to create strings.
• Strings are objects of class String.
• Double-quoted strings allow substitution and
backslash notation but single-quoted strings
doesn’t allow substitution and allow backslash
notation only for \\ and \’.
• Example:
# Ruby program to illustrate the
# Strings Data Type
#!/usr/bin/ruby -w
puts "String Data Type";
puts 'escape using "\\"';
puts 'That\'s right';
Output:
String Data Type
escape using "\"
That's right
Hashes
• A hash assign its values to its key.
• Value to a key is assigned by => sign.
• A key pair is separated with a comma
between them and all the pairs are
enclosed within curly braces.
• A hash in Ruby is like an object literal in
JavaScript or an associative array in PHP.
• They’re made similarly to arrays.
• A trailing comma is ignored.
• Example:
# Ruby program to illustrate the
# Hashes Data Type
#!/usr/bin/ruby
hsh = colors = { "red" => 0xf00, "green" =>
0x0f0, "blue" => 0x00f }
hsh.each do |key, value|
print key, " is ", value, "\n"
end Output:
red is 3840
green is 240
blue is 15
Arrays
• An array stores data or list of data.
• It can contain all types of data.
• Data in an array are separated by
comma in between them and are
enclosed within square bracket.
• The position of elements in an array
starts with 0. A trailing comma is
ignored.
• Example:
# Ruby program to illustrate the
# Arrays Data Type
#!/usr/bin/ruby
ary = [ "fred", 10, 3.14, "This is a string", "last
element", ]
ary.each do |i|
Output:
puts i
fred
end
10
3.14
This is a string
last element
Symbols
• Symbols are light-weight strings.
• A symbol is preceded by a colon (:).
• They are used instead of strings
because they can take up much less
memory.
• Symbols have better performance.
• Example:
• # Ruby program to illustrate the
• # Symbols Data Type
• #!/usr/bin/ruby
• domains = {:sk => "GeeksforGeeks", :no =>
"GFG", :hu => "Geeks"}
• puts domains[:sk] Output:
• puts domains[:no] GeeksforGeeks
• puts domains[:hu] GFG
Geeks
Most Common Ruby
Array Methods
• Ruby Arrays form a core foundation in programming in
Ruby, and most languages in fact.
• It is used so much that it would be beneficial to know and
even memorize some of the most commonly used
methods for arrays.
• For the purpose of this guide, our array will be as follows:
array = [0, 1, 2, 3, 4]
• .length : The .length method tallies the number of
elements in your array and returns the count:
array.length
=> 5
• .first : The .first method accesses the first element of the
array, the element at index 0:
array.first
=> 0
• .last : The .last method accesses the last element of the
array:
array.last
=> 4
• .take : The .take method returns the first n elements of the
array:
array.take(3)
=> [0, 1, 2]
• .drop : The .drop method returns the elements after n
elements of the array:
array.drop(3)
• array index : You can access a specific element in an array by
accessing its index. If the index does not exist in the array, nil
will be returned:
array[2]
=> 2
array[5]
=> nil
• .pop : The .pop method will permantently remove the last
element of an array:
array.pop
=> [0, 1, 2, 3]
• .shift : The .shift method will permantently remove the first
element of an array and return this element:
array.shift
=> 0
array
• .push : The .push method will allow you to add an element to the
end of an array:
array.push(99)
=> [0, 1, 2, 3, 4, 99]
• .unshift : The .unshift method will allow you to add an element to
the beginning of an array:
array = [2, 3]
array.unshift(1)
=> [1, 2, 3]
• .delete : The .delete method removes a specified element from
an array permanently:
array.delete(1)
=> [0, 2, 3, 4]
• .delete_at : The .delete_at method allows you to permanently
remove an element of an array at a specified index:
array.delete_at(0)
=> [1, 2, 3, 4]
• .reverse : The .reverse method reverses the array but
does not mutate it (the original array stays as is):
array.reverse
=> [4, 3, 2, 1, 0]
• .select : The .select method iterates over an array and
returns a new array that includes any items that return
true to the expression provided.
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.select { |number| number > 4 }
=> [5, 6, 7, 8, 9, 10]
array
=> [5, 6, 7, 8, 9, 10]
• .include?
• The include? method checks to see if the argument given
is included in the array:
array = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
array.include?(3)
=> true
#### .flatten
The flatten method can be used to take an array that
contains nested arrays and create a one-dimensional
array:
``` ruby
array = [1, 2, [3, 4, 5], [6, 7]]
array.flatten
=> [1, 2, 3, 4, 5, 6, 7]
• .join : The .join method returns a string of all the elements of the
array separated by a separator parameter. If the separator
parameter is nil, the method uses an empty string as a separator
between strings.
array.join
=> "1234"
array.join("*")
=> "1*2*3*4"
• .each : The .each method iterates over each element of the array,
allowing you to perform actions on them.
array.each do |element|
puts element
end
=>
0
1
2
3
• .map : The .map method is the same as the .collect method. The .map
and .collect methods iterate over each element of the array, allowing you
to perform actions on them. The .map and .collect methods differ from the
.each method in that they return an array containing the transformed
elements.
array.map { |element| element * 2 }
puts element
end
=>
0
2
4
6
8
• .uniq : The .uniq method takes in an array containing duplicate elements,
and returns a copy of the array containing only unique elements—any
duplicate elements are removed from the array.
array = [1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 6, 7, 8]
array.uniq
=> [1, 2, 3, 4, 5, 6, 7, 8]
• .concat
• The .concat method appends the elements from
an array to the original array.
• The .concat method can take in multiple arrays
as an argument, which will in turn append
multiple arrays to the original array.
array = [0, 1, 2, 3, 4]
array.concat([5, 6, 7], [8, 9, 10])
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Ruby Strings
• Ruby string object holds and manipulates an arbitary
sequence of bytes, typically representing characters.
• They are created using String::new or as literals.
• arbitary sequence of bytes, typically representing
characters. They are created using String::new or as
literals.
• Quotes : Ruby string literals are enclosed within single
and double quotes.
• Example:
#!/usr/bin/ruby
puts 'Hello everyone'
puts "Hello everyone"
• Accessing string elements
• You can access Ruby string elements in different parts with
the help of square brackets [ ].
• Within square brackets write the index or string.
• Example:
#!/usr/bin/ruby
msg = "This tutorial is from JavaTpoint."
puts msg["JavaTpoint"]
puts msg["tutorial"]
puts msg[0]
puts msg[0, 2]
puts msg[0..19]
puts msg[0, msg.length]
puts msg[-3]
Ruby String Methods
• Ruby has many built in methods to work with
strings.
• Strings in Ruby by default are mutable and can
be changed in place or a new string can be
returned from a method.
• Length
• The .length property returns the number of
characters in a string including white-space.
"Hello".length #=> 5
"Hello World!".length #=> 12
• Empty
• The .empty? method returns true if a string has a length
of zero.
"Hello".empty? #=> false
"!".empty? #=> false
" ".empty? #=> false
"".empty? #=> true
• Count
• The .count method counts how many times a specific
character(s) is found in a string.
• This method is case-sensitive.
"HELLO".count('L') #=> 2
"HELLO WORLD!".count('LO') #=> 1
• Insert
• The .insert method inserts a string into another string
before a given index.
"Hello".insert(3, "hi5") #=> Helhi5lo # "hi5" is inserted
into the string right before the second 'l' which is at
index 3
• Upcase
• The .upcase method transforms all letters in a string to
uppercase.
"Hello".upcase #=> HELLO
• Downcase
• The .downcase method transforms all letters in a string to
lowercase.
"Hello".downcase #=> hello
• Swapcase
• The .swapcase method transforms the uppercase latters
in a string to lowercase and the lowercase letters to
uppercase.
"hELLO wORLD".swapcase #=> Hello World
• Capitalize
• The .capitalize method make the first letter in a string
uppercase and the rest of the string lowercase.
"HELLO".capitalize #=> Hello
"HELLO, HOW ARE YOU?".capitalize #=> Hello, how are
you?
• Note that the first letter is only capitalized if it is at the
beginning of the string. ruby
"-HELLO".capitalize #=> -hello "1HELLO".capitalize #=>
• Reverse
• The .reverse method reverses the order of the characters
in a string.
"Hello World!".reverse #=> "!dlroW olleH"
• Split
• The .split takes a strings and splits it into an array, then
returns the array.
"Hello, how are you?".split #=> ["Hello,", "how", "are",
"you?"]
• The default method splits the string based on whitespace,
unless a different separator is provided (see second
example).
"H-e-l-l-o".split('-') #=> ["H", "e", "l", "l", "o"]
• Chop
• The .chop method removes the last character of
the string.
• A new string is returned, unless you use
the .chop! method which mutates the original
string.
"Name".chop #=> Nam
name = "Batman"
name.chop
name == "Batma" #=> false
name = "Batman"
name.chop!
name == "Batma" #=> true
• Strip
• The .strip method removes the leading and trailing
whitespace on strings, including tabs, newlines, and
carriage returns (\t, \n, \r).
" Hello ".strip #=> Hello
• Chomp
• The .chomp method removes the last character in a string,
only if it’s a carriage return or newline (\r, \n).
• This method is commonly used with the gets command to
remove returns from user input.
"hello\r".chomp #=> hello
"hello\t".chomp #=> hello\t # because tabs and other
whitespace remain intact when using `chomp`
• To Integer : The .to_i method converts a string
to an integer.
"15".to_i #=> 15 # integer
• Gsub
• gsub replaces every reference of the first
parameter for the second parameter on a string.
"ruby is cool".gsub("cool", "very cool") #=>
"ruby is very cool"
• gsub also accepts patterns (like regexp) as first
parameter, allowing things like:
"ruby is cool".gsub(/[aeiou]/, "*") #=> "r*by
*s c**l"
• Concatenation
• Ruby implements some methods to concatenate two
strings together.
• The + method:
"15" + "15" #=> "1515" # string
• The << method:
"15" << "15" #=> "1515" # string
• The concat method:
"15".concat "15" #=> "1515" # string
• Clear
• Removes string content.
a = "abcde"
a.clear #=> ""
• Index
• The index method returns the index position of the first
occurrence of the substring or regular expression
pattern match in a string.
• If there is no match found, nil is returned.
• A second optional parameter indicates which index
position in the string to begin searching for a match.
"information".index('o') #=> 3
"information".index('mat') #=> 5
"information".index(/[abc]/) #=> 6
"information".index('o', 5) #=> 9
"information".index('z') #=> nil
Code Iterators Ruby
• The word iterate means doing one thing multiple times
and that is what iterators do. Sometimes iterators are
termed as the custom loops.
• “Iterators” is the object-oriented concept in Ruby.
• In more simple words, iterators are the methods which
are supported by collections(Arrays, Hashes etc.).
• Collections are the objects which store a group of data
members.
• Ruby iterators return all the elements of a collection one
after another.
• Ruby iterators are “chainable” i.e adding functionality on
top of each other.
Types of Iterators
• There are many iterators in Ruby as follows:
1. Each Iterator
2. Collect Iterator
3. Times Iterator
4. Upto Iterator
5. Downto Iterator
6. Step Iterator
7. Each_Line Iterator
• Each Iterator: This iterator returns all the
elements of an array or a hash. Each iterator
returns each value one by one.
• Syntax:
collection.each do |variable_name|
# code to be iterate
end
• In the above syntax, the collection can be the
range, array or hash.
# Ruby program to illustrate each iterator
#!/usr/bin/ruby
# using each iterator Output:
# here collection is range 0
# variable name is i 1
2
(0..9).each do |i|
3
# statement to be executed
4
puts i 5
end 6
a = ['G', 'e', 'e', 'k', 's'] 7
puts "\n" 8
# using each iterator 9
# here collection is an array G
a.each do|arr| e
# statement to be executed e
puts arr k
• Collect Iterator: This iterator returns all the
elements of a collection.
• The collect iterator returns an entire collection,
regardless of whether it is an array or hash.
• Syntax:
Collection = collection.collect
• The collect method need not always be associated
with a block.
• The collect method returns the entire collection,
regardless of whether it is an array or a hash.
# Ruby program to illustrate the collect
iterator
#!/usr/bin/ruby Output:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 5
# using collect iterator 10
# printing table of 5 15
20
b = a.collect{ |y| (5 * y) } 25
puts b 30
35
40
45
50
• Times Iterator: In this iterator, a loop is
implanted with the specific number of time.
• The loop is initially started from zero and runs
until the one less than the specified number.
• This can be used with no iteration variable.
• We can add an iteration variable by using the
vertical bars around the identifier.
• Syntax:
t.times do |variable_name|
# code to be execute
end
• Here t is the specified number which is used to
define the number of iteration
# Ruby program to illustrate time iterator
#!/usr/bin/ruby
# using times iterator by providing
# 7 as the iterate value
7.times do |i| Output:
puts i 0
end 1
2
3
4
5
6
• Upto Iterator: This iterator follows top to bottom
approach.
• It includes both the top and bottom variable in the
iteration.
• Syntax:
top.upto(bottom) do |variable_name|
# code to execute
end
• Here iteration starts from top and ends on bottom.
• The important point to remember that the value of
bottom variable is always greater than the top variable
and if it is not, then it will return nothing.
# Ruby program to illustrate the upto iterator
#!/usr/bin/ruby
# using upto iterator
# here top value is 4
# bottom value is 7
4.upto(7) do |n| Output:
puts n
end 4
# here top > bottom 5
# so no output 6
7.upto(4) do |n| 7
puts n
end
• Downto Iterator: This iterator follows bottom
to top approach. It includes both the top and
bottom variable in the iteration.
• Syntax:
top.downto(bottom) do |variable_name|
# code to execute
end
• Here iteration starts from bottom and ends on
top.
• The important point to remember that the value
of bottom variable is always smaller than the top
variable and if it is not, then it will return
nothing.
# Ruby program to illustrate the downto iterator
#!/usr/bin/ruby
# using downto iterator
# here top value is 7
# bottom value is 4
7.downto(4) do |n|
puts n
end
Output:
# here top < bottom
# so no output 7
4.downto(7) do |n| 6
puts n 5
end 4
• Step Iterator: Ruby step iterator is used
to iterate where the user has to skip a
specified range.
• Syntax:
Collection.step(rng) do |variable_name|
# code to be executed
end
• Here rng is the range which will be skipped
throughout the iterate operation.
# Ruby program to illustrate step
iterator
#!/usr/bin/ruby
# using step iterator Output:
# skipping value is 10
# (0..60 ) is the range 0
10
(0..60).step(10) do|i|
20
puts i 30
end 40
50
60
• Each_line Iterator:
• Ruby each_line iterator is used to iterate over a
new line in the string.
• Syntax:
string.each_line do |variable_name|
# code to be executed
end
# Ruby program to illustrate Each_line iterator
#!/usr/bin/ruby
# using each_line iterator
"Welcome\nto\nGeeksForGeeks\
nPortal".each_line do|i|
puts i
end Output:
Welcome
to
GeeksForGeeks
Portal