0% found this document useful (0 votes)
5 views

Introduction to Ruby and Rails

Ruby is a dynamic, open-source, object-oriented programming language designed by Yukihiro Matsumoto in the mid-1990s. It emphasizes simplicity and productivity, featuring flexible syntax and a focus on the principle of least astonishment. The document covers Ruby's history, features, data types, variable types, and basic syntax, along with examples of its usage.

Uploaded by

Manasa M R
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Introduction to Ruby and Rails

Ruby is a dynamic, open-source, object-oriented programming language designed by Yukihiro Matsumoto in the mid-1990s. It emphasizes simplicity and productivity, featuring flexible syntax and a focus on the principle of least astonishment. The document covers Ruby's history, features, data types, variable types, and basic syntax, along with examples of its usage.

Uploaded by

Manasa M R
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 83

Introduction to Ruby

• Ruby is a dynamic, open source, object oriented and


reflective programming language.
• Ruby is considered similar to Perl and Smalltalk
programming languages. It runs on all types of platforms
like Windows, Mac OS and all versions of UNIX.
• It is fully object oriented programming language.
Everything is an object in Ruby. Each and every code has
their properties and actions. Here properties refer to
variables and actions refer to methods.
• Ruby is considered to follow the principle of POLA
(principle of least astonishment).
• It means that the language behaves in such a way to
minimize the confusion for experienced users.
• History of Ruby?
• Ruby is designed and developed by Yukihiro "Martz"
Matsumoto in mid 1990s in Japan.
• Idea of Ruby?
• Perl is a scripting language but comes under the category
of Toy language.
• Python is not fully object oriented language. Ruby
developer Yukihiro "Martz" Matsumoto wanted a
programming language which is completely object
oriented and should be easy to use as a scripting
language.
• Ruby in Present
• The current Ruby version 2.4.0 was released on
Christmas in 2016. It has several new features like
improvement to hash table, instance variable access,
Ruby Versions
• There are many Ruby versions have been released
till date.
• Version 1.8 (4th Aug, 2003)
• Version 1.9 (25th Dec, 2007)
• Version 2.0 (24th Feb, 2013)
• Version 2.1 (25th Dec, 2013)
• Version 2.2 (25th Dec, 2014)
• Version 2.3 (25th Dec, 2015)
• Version 2.4 (25th Dec, 2016) Current stable Ruby
version
• Version 3.0 (Future Release)
1.Object Oriented : Ruby is purely object oriented
programming language.
• Each and every value is an object.
• Every object has a class and every class has a super
class.
• Every code has their properties and actions.
• Ruby is influenced with Smalltalk language.
• Rules applying to objects applies to the entire.
2.Flexibility : Ruby is a flexible language as you can
easily remove, redefine or add existing parts to it.
• It allows its users to freely alter its parts as they
wish.
3.Mixins : Ruby has a feature of single inheritance
only.
• Ruby has classes as well as modules.
• A module has methods but no instances.
• Instead, a module can be mixed into a class,
which adds the method of that module to the
class.
• It is similar to inheritance but much more flexible.
4. Visual appearance : Ruby generally prefers
English keyword and some punctuation is used to
decorate Ruby.
• It doesn't need variable declaration.
5. Dynamic typing and Duck typing
• Ruby is a dynamic programming language. Ruby programs
are not compiled.
• All class, module and method definition are built by the code
when it run.
• Ruby variables are loosely typed language, which means any
variable can hold any type of object.
• When a method is called on an object, Ruby only looks up at
the name irrespective of the type of object.
• This is duck typing. It allows you to make classes that pretend
to be other classes.
6. Variable constants
• In Ruby, constants are not really constant.
• If an already initialized constant will be modified in a script, it
will simply trigger a warning but will not halt your program.
7. Naming conventions
• Ruby defines some naming conventions for its variable, method,
constant and class.
• Constant: Starts with a capital letter.
• Global variable: Starts with a dollar sign ($).
• Instance variable: Starts with a (@) sign.
• Class variable: Starts with a (@@) sign.
• Method name: Allowed to start with a capital letter.
8. Keyword arguments
• Like Python, Ruby methods can also be defined using keyword
arguments.
9.Method names
• Methods are allowed to end with question mark (?) or exclamation
mark (!).
• By convention, methods that answer questions end with question
mark and methods that indicates that method can change the state
10. Singleton methods
• Ruby singleton methods are per-object methods. They are
only available on the object you defined it on.
11.Missing method
• If a method is lost, Ruby calls the method_missing method
with name of the lost method.
12. Statement delimiters
• Multiple statements in a single line must contain semi colon
in between but not at the end of a line.
13.Keywords
• In Ruby there are approximately 42 keywords which can't be
used for other purposes. They are called reserved words.
14. Case Sensitive
• Ruby is a case-sensitive language. Lowercase letters and
uppercase letters are different.
Popular Ruby Editors
• To write your Ruby programs, you will need an editor.
1. If you are working on Windows machine, then you can
use any simple text editor like Notepad or Edit plus.
2. VIM (Vi IMproved) is a very simple text editor. This is
available on almost all Unix machines and now
Windows as well. Otherwise, your can use your favorite
vi editor to write Ruby programs.
3. RubyWin is a Ruby Integrated Development
Environment (IDE) for Windows.
4. Ruby Development Environment (RDE) is also a very
good IDE for windows users.
Hello Ruby Program
• Now we will write a simple program of Ruby.
Before writing Hello World program, we are
assuming that you have successfully installed Ruby
in your system.
• Requirement for Hello Ruby Program
Download Ruby and install it.
Create a file with .rb extension.
Connect Ruby path to the file.
Run the file.
Creating Hello Ruby
Program
1. Use any text editor and create a hello.rb file.
Write the following code,
puts "Hello Ruby !"
2. Connect Ruby path to the above file.
• We have created hello.rb file in the Desktop.
• So first we need to go the Desktop directory
through our console.
3. Run the following command.
ruby hello.rb
Ruby Basic Syntax
• To program in Ruby is easy to learn because of its
similar syntax to already widely used languages.
• Here, we will learn the basic syntax of Ruby
language.
• Let us write a simple program to print “Hello
World!”.
• # this line will print "Hello World!" as output.
puts "Hello World!";
Output:
Hello World!
• End of a line in Ruby
• Ruby interprets newline characters(\n) and semicolons(;) as
the end of a statement.
• Note: If a line has +, – or backslash at the end of a line, then
it indicates the continuation of a statement.
• Whitespace in Ruby
• Whitespace characters such as spaces and tabs are generally
ignored in Ruby code, except when they appear in a string,
i.e. it ignores all spaces in a statement But sometimes,
whitespaces are used to interpret ambiguous statements.
• Example :
• a / b interprets as a/b (Here a is a variable)
• a b interprets as a(b)
• (Here a is a method)
# declaring a function named 'a' which accepts an
# integer and return 1
def a(u) return 1 end Output:
# driver code 5
a=3 1
b=2
# this a + b interprets as a + b, so prints 5 as output
puts(a + b)
# this a b interprets as a(b) thus the returned
# value is printed
puts(a b)
• Ruby BEGIN and END statement
• BEGIN statement is used to declare a part of code which must
be called before the program runs.
• Syntax:
BEGIN
{
# code written here
}
• Similarly, END is used to declare a part of code which must be
called at the end of program.
• Syntax:
END
{
# code written here
}
Example of BEGIN and END
# Ruby program of BEGIN and END
puts "This is main body of program"

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:

Symbol Type of Variable

[a-z] or _ Local Variable

@ 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

You might also like