SlideShare a Scribd company logo
1 of 15
Ruby Data Types and Object - Module 2
● Numbers
● Text
● Arrays and Hashes
● Ranges
● Symbols
● Reserved Keywords
● Objects
Numbers
Integer -
Fixnum - If an integer value fits within 31 bits (on most implementations), it is an instance of Fixnum.
Bignum
The Complex, BigDecimal, and Rational classes are not built-in to Ruby but are distributed with Ruby as part of
the standard library.
All numeric objects are immutable
0377 # Octal representation of 255
0b1111_1111 # Binary representation of 255
0xFF # Hexadecimal representation of 255
Float
0.0
-3.14
Text
Text is represented in Ruby by objects of the String class. Strings are mutable objects.
“test”.object_id # 123989
“test”.object_id # 987654
Single Quoted String:
'This is a simple Ruby string literal'
'Won't you read O'Reilly's book?' # backslash for using apostrophes in single quoted string
Double Quoted String:
“I am in double quotes”
String interpolation:
“Pi value in Ruby #{Math::PI}” # pi value in ruby 3.141592…
Arbitrary delimiters for string literals:
%q(test) # returns ‘test’
%Q(test) # returns “test”
Text(Refer http://www.ruby-doc.org/core-2.1.2/String.html)
String Concatenation:
● + operator is used for string concatanation
“test” + RUBY_VARIABLE + “string”
“test something” + new.to_s # to_s converts to a string
test = “I am learning Ruby”
● The << operator appends its second operand to its first
test << “Ruby is very simple”
● The * operator expects an integer as its righthand operand
ellipsis = '.'*3 # Evaluates to '...'
Accessing Characters and Substrings:
● s = 'hello'
s[0] # will return the first character of the string
s[-1] # will return the last character of the string
s.length # will return the length of the string
s[-1] = “” # will delete the last character
s[-1] = “p” # will change the last character and new string will be “help” now.
s[0, 2] # wil return the first two character : “he”
s[-1, 1] # will return the last character : “o”
Iterating Strings:
each_char upto each each_byte methods are used for string iteration.
‘hello’.each_char {|c| puts c}
0.upto(‘hello’.size - 1) { |c| puts c}
Arrays
An Array is a sequence of values that allows values to be accessed by their position, or index, in the sequence.
In Ruby
● The first value in an array has index 0.
● Arrays are untyped and mutable.
● The elements of an array need not all be of the same class, and they can be changed at any time.
● The size and length methods return the number of elements in an array.
○ [1, 2, 3] # An array that holds three Fixnum objects
○ [-10...0, 0..10,] # An array of two ranges; trailing commas are allowed
○ [[1,2],[3,4],[5]] # An array of nested arrays
○ [] # The empty array has size 0
○ let’s say a = [1, 1, 2, 2, 3, 3, 4] , b = [5, 5, 4, 4, 3, 3, 2] then
■ a | b # [1, 2, 3, 4, 5]: duplicates are removed
■ b | a # [5, 4, 3, 2, 1]: elements are the same, but order is different
■ a & b # [2, 3, 4] : only common elements are present
Array methods - clear, compact!, delete_if, each_index, empty?, fill, flatten!, include?, index, join, pop, push, reverse,
reverse_each, rindex, shift, sort, sort!, uniq!, and unshift.
Array
Different ways for Array declaration and obtaining the value of Array element:
● words = %w[this is a test] # Same as: ['this', 'is', 'a', 'test']
● white = %W(s t r n) # Same as: ["s", "t", "r", "n"]
● empty = Array.new # []: returns a new empty array
● nils = Array.new(3) # [nil, nil, nil]: new array with 3 nil elements
● copy = Array.new(nils) # Make a new copy of an existing array
● zeros = Array.new(4, 0) # [0, 0, 0, 0]: new array with 4 0 elements
Let’s say a = [1, 2, 6, 7, 9]
● a[0] # returns the first element - 1
● a[-1] # return the last element - 9
Array element assignments
● a[0] = "zero" # a is ["zero", 2, 6, 7, 9]
● a[-1] = 0 # a is ["zero", 2, 6, 7, 0]
Array(Refer : http://www.ruby-doc.org/core-2.1.2/Array.html)
Like strings, arrays can also be indexed with two integers that represent a starting index and a number of
elements, or a Range object.
● a = ('a'..'e').to_a # Range converted to ['a', 'b', 'c', 'd', 'e']
● a[0,0] # []: this subarray has zero elements
● a[1,1] # ['b']: a one-element array
● a[-2,2] # ['d','e']: the last two elements of the array
A subarray can be replaced by the elements of the array on the righthand side
● a[0,2] = ['A', 'B'] # a becomes ['A', 'B', 'c', 'd', 'e']
● a[2...5]=['C', 'D', 'E'] # a becomes ['A', 'B', 'C', 'D', 'E']
● a = a + [[6, 7, 8]] # a becomes ['A', 'B', 'C', 'D', 'E', [6, 7, 8]]
Use << to append elements to the end of an existing array and - to remove array elements
a = [] # empty array
a << 3 # a becomes [3]
['a', 'b', 'c', 'b', 'a'] - ['b', 'c', 'd'] # results ['a', 'a']
a = [0] * 8 # a becomes [0, 0, 0, 0, 0, 0, 0, 0]
Hashes
A hash or maps or associative arrays is a data structure that maintains a set of objects known as keys, and associates a value with
each key.
Hash Initialize
numbers = Hash.new or numbers = {} # Create a new, empty, hash object
Hash key/value Assignment
numbers["one"] = 1 # Map the String "one" to the Fixnum 1
numbers["two"] = 2 # Note that we are using array notation here
Or
numbers = { "one" => 1, "two" => 2, "three" => 3 } # ruby 1.8
Or
numbers = { one: 1, two: 2, three: 3 } # ruby 1.9
Hash value Retrieve
sum = numbers["one"] + numbers["two"] # Retrieve values like this
Iterate over a hash
numbers = { one: 1, two: 2, three: 3 }
numbers.each { |key, value|
puts “key….. #{key}”
puts “value ….#{value}”
}
Array of Hashes
h = [{one: 1}, {two: 2}, {three: 3}]
Ranges
A Range object represents the values between a start value and an end value.
Range Literals:
1..10 # The integers 1 through 10, including 10
1…10 # The integers 1 through 10, excluding 10
Usage:
years = 1990..2014
my_birthday = 1998
years.include?(my_birthday) # Returns true
string = 'a'..'c‘
string.each { |s| puts s } # prints a b c
Note: The Range class defines methods for determining whether an arbitrary value is a member of (i.e., is included in) a range.
Symbols
In Ruby
 Symbols are Strings, just with an important difference –
 Symbols are immutable.
 A symbol literal is written by prefixing an identifier or string with a colon.
 Mutable objects can be changed after assignment while immutable objects can only be overwritten.
Symbols interpolation and operations:
t = :test # Here t is a symbol
s = %s(symbol) # :symbol
:”test #{s}” # :”test symbol”
Symbol to String Conversion
s = “string”
s.intern or s.to_sym # converts the string in to symbol
:test.to_s or :test.id2name # convers symbol to string
Reserved Keywords
Reserved word Description
BEGIN Code, enclosed in { and }, to run before the program runs.
END Code, enclosed in { and }, to run when the program ends.
alias Creates an alias for an existing method, operator, or global variable.
and Logical operator; same as && except and has lower precedence.
begin Begins a code block or group of statements; closes with end.
break Terminates a while or until loop or a method inside a block.
case Compares an expression with a matching when clause; closes with end.
class Defines a class; closes with end.
def Defines a method; closes with end.
defined? Determines if a variable, method, super method, or block exists.
do Begins a block and executes code in that block; closes with end.
else Executes if previous conditional, in if, elsif, unless, or when, is not true.
elsif Executes if previous conditional, in if or elsif, is not true.
end Ends a code block (group of statements) starting with begin, def, do, if, etc.
ensure Always executes at block termination; use after last rescue.
Reserved Keywords
Reserved word Description
false Logical or Boolean false, instance of FalseClass. (See true.)
for Begins a for loop; used with in.
if Executes code block if true. Closes with end.
module Defines a module; closes with end.
next Jumps before a loop's conditional.
nil Empty, uninitialized variable, or invalid, but not the same as zero; object of NilClass.
not Logical operator; same as !.
or Logical operator; same as || except or has lower precedence.
redo Jumps after a loop's conditional.
rescue Evaluates an expression after an exception is raised; used before ensure.
retry Repeats a method call outside of rescue; jumps to top of block (begin) if inside rescue.
return Returns a value from a method or block. May be omitted.
self Current object (invoked by a method).
super Calls method of the same name in the superclass. The superclass is the parent of this class.
then A continuation for if, unless, and when. May be omitted.
Reserved Keywords
Reserved word Description
true Logical or Boolean true, instance of TrueClass.
undef Makes a method in current class undefined.
unless Executes code block if conditional statement is false.
until Executes code block while conditional statement is false.
when Starts a clause (one or more) under case.
while Executes code while the conditional statement is true.
yield Executes the block passed to the method.
_ _FILE_ _ Name of current source file.
_ _LINE_ _ Number of current line in the current source file.
Objects
Ruby is a very pure object-oriented language: all values are objects.
Object References - When we work with objects in Ruby, we are really working with object references.
s = “string” # Create a String object. Store a reference to it in s.
t = s # Copy the reference to t. s and t both refer to the same object.
Object Lifetime - Ruby uses garbage collection means that Ruby programs are less susceptible to memory leaks than programs
written in languages that require objects and memory to be explicitly deallocated and freed. Object lifetime is till then it is reachable.
Different operations on Object and object conversion:
The equal? Method
a = “test”
b = c = “test”
a.equal?(b) # false : a and b are different objects
b.equal?(c) # true
The == operator
a == b # true
Note: equal? Method works like check object_id of two objects and == operators works with the content of the
two objects
Conversions - to_i, to_s, to_h, to_sym, to_f, to_a
Tainted object - When a object has it's tainted flag set, that means, roughly, that the object came from an unreliable source and
therefore can't be used in sensitive operations.
a = “test”.taint

More Related Content

What's hot

String handling session 5
String handling session 5String handling session 5
String handling session 5Raja Sekhar
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)Ravi Kant Sahu
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and StringsEduardo Bergavera
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arraysphanleson
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaRasan Samarasinghe
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)Anwar Hasan Shuvo
 
Strings in Python
Strings in PythonStrings in Python
Strings in Pythonnitamhaske
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)teach4uin
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi Kant Sahu
 
String in python lecture (3)
String in python lecture (3)String in python lecture (3)
String in python lecture (3)Ali ٍSattar
 

What's hot (18)

String handling session 5
String handling session 5String handling session 5
String handling session 5
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
M C6java2
M C6java2M C6java2
M C6java2
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
M C6java7
M C6java7M C6java7
M C6java7
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
 
Chapter 7 String
Chapter 7 StringChapter 7 String
Chapter 7 String
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
 
Strings
StringsStrings
Strings
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
 
M C6java3
M C6java3M C6java3
M C6java3
 
Java strings
Java   stringsJava   strings
Java strings
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
String in python lecture (3)
String in python lecture (3)String in python lecture (3)
String in python lecture (3)
 

Similar to Ruby data types and objects

RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0tutorialsruby
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in PythonSujith Kumar
 
Quick python reference
Quick python referenceQuick python reference
Quick python referenceJayant Parida
 
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular  Expressions,  Dictionaries.pdfModule 3 - Regular  Expressions,  Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdfGaneshRaghu4
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to heroDiego Lemos
 
Regular expressions
Regular expressionsRegular expressions
Regular expressionsRaghu nath
 
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxCS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxfaithxdunce63732
 
Sort Characters in a Python String Alphabetically
Sort Characters in a Python String AlphabeticallySort Characters in a Python String Alphabetically
Sort Characters in a Python String AlphabeticallyKal Bartal
 

Similar to Ruby data types and objects (20)

Lecture 7
Lecture 7Lecture 7
Lecture 7
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Python slide.1
Python slide.1Python slide.1
Python slide.1
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
Ruby_Basic
Ruby_BasicRuby_Basic
Ruby_Basic
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
 
06 ruby variables
06 ruby variables06 ruby variables
06 ruby variables
 
Quick python reference
Quick python referenceQuick python reference
Quick python reference
 
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular  Expressions,  Dictionaries.pdfModule 3 - Regular  Expressions,  Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdf
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to hero
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
easyPy-Basic.pdf
easyPy-Basic.pdfeasyPy-Basic.pdf
easyPy-Basic.pdf
 
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxCS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
 
python.pdf
python.pdfpython.pdf
python.pdf
 
Java Script Introduction
Java Script IntroductionJava Script Introduction
Java Script Introduction
 
UNIT 4 python.pptx
UNIT 4 python.pptxUNIT 4 python.pptx
UNIT 4 python.pptx
 
Sort Characters in a Python String Alphabetically
Sort Characters in a Python String AlphabeticallySort Characters in a Python String Alphabetically
Sort Characters in a Python String Alphabetically
 

Recently uploaded

Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 

Recently uploaded (20)

Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 

Ruby data types and objects

  • 1. Ruby Data Types and Object - Module 2 ● Numbers ● Text ● Arrays and Hashes ● Ranges ● Symbols ● Reserved Keywords ● Objects
  • 2.
  • 3. Numbers Integer - Fixnum - If an integer value fits within 31 bits (on most implementations), it is an instance of Fixnum. Bignum The Complex, BigDecimal, and Rational classes are not built-in to Ruby but are distributed with Ruby as part of the standard library. All numeric objects are immutable 0377 # Octal representation of 255 0b1111_1111 # Binary representation of 255 0xFF # Hexadecimal representation of 255 Float 0.0 -3.14
  • 4. Text Text is represented in Ruby by objects of the String class. Strings are mutable objects. “test”.object_id # 123989 “test”.object_id # 987654 Single Quoted String: 'This is a simple Ruby string literal' 'Won't you read O'Reilly's book?' # backslash for using apostrophes in single quoted string Double Quoted String: “I am in double quotes” String interpolation: “Pi value in Ruby #{Math::PI}” # pi value in ruby 3.141592… Arbitrary delimiters for string literals: %q(test) # returns ‘test’ %Q(test) # returns “test”
  • 5. Text(Refer http://www.ruby-doc.org/core-2.1.2/String.html) String Concatenation: ● + operator is used for string concatanation “test” + RUBY_VARIABLE + “string” “test something” + new.to_s # to_s converts to a string test = “I am learning Ruby” ● The << operator appends its second operand to its first test << “Ruby is very simple” ● The * operator expects an integer as its righthand operand ellipsis = '.'*3 # Evaluates to '...' Accessing Characters and Substrings: ● s = 'hello' s[0] # will return the first character of the string s[-1] # will return the last character of the string s.length # will return the length of the string s[-1] = “” # will delete the last character s[-1] = “p” # will change the last character and new string will be “help” now. s[0, 2] # wil return the first two character : “he” s[-1, 1] # will return the last character : “o” Iterating Strings: each_char upto each each_byte methods are used for string iteration. ‘hello’.each_char {|c| puts c} 0.upto(‘hello’.size - 1) { |c| puts c}
  • 6. Arrays An Array is a sequence of values that allows values to be accessed by their position, or index, in the sequence. In Ruby ● The first value in an array has index 0. ● Arrays are untyped and mutable. ● The elements of an array need not all be of the same class, and they can be changed at any time. ● The size and length methods return the number of elements in an array. ○ [1, 2, 3] # An array that holds three Fixnum objects ○ [-10...0, 0..10,] # An array of two ranges; trailing commas are allowed ○ [[1,2],[3,4],[5]] # An array of nested arrays ○ [] # The empty array has size 0 ○ let’s say a = [1, 1, 2, 2, 3, 3, 4] , b = [5, 5, 4, 4, 3, 3, 2] then ■ a | b # [1, 2, 3, 4, 5]: duplicates are removed ■ b | a # [5, 4, 3, 2, 1]: elements are the same, but order is different ■ a & b # [2, 3, 4] : only common elements are present Array methods - clear, compact!, delete_if, each_index, empty?, fill, flatten!, include?, index, join, pop, push, reverse, reverse_each, rindex, shift, sort, sort!, uniq!, and unshift.
  • 7. Array Different ways for Array declaration and obtaining the value of Array element: ● words = %w[this is a test] # Same as: ['this', 'is', 'a', 'test'] ● white = %W(s t r n) # Same as: ["s", "t", "r", "n"] ● empty = Array.new # []: returns a new empty array ● nils = Array.new(3) # [nil, nil, nil]: new array with 3 nil elements ● copy = Array.new(nils) # Make a new copy of an existing array ● zeros = Array.new(4, 0) # [0, 0, 0, 0]: new array with 4 0 elements Let’s say a = [1, 2, 6, 7, 9] ● a[0] # returns the first element - 1 ● a[-1] # return the last element - 9 Array element assignments ● a[0] = "zero" # a is ["zero", 2, 6, 7, 9] ● a[-1] = 0 # a is ["zero", 2, 6, 7, 0]
  • 8. Array(Refer : http://www.ruby-doc.org/core-2.1.2/Array.html) Like strings, arrays can also be indexed with two integers that represent a starting index and a number of elements, or a Range object. ● a = ('a'..'e').to_a # Range converted to ['a', 'b', 'c', 'd', 'e'] ● a[0,0] # []: this subarray has zero elements ● a[1,1] # ['b']: a one-element array ● a[-2,2] # ['d','e']: the last two elements of the array A subarray can be replaced by the elements of the array on the righthand side ● a[0,2] = ['A', 'B'] # a becomes ['A', 'B', 'c', 'd', 'e'] ● a[2...5]=['C', 'D', 'E'] # a becomes ['A', 'B', 'C', 'D', 'E'] ● a = a + [[6, 7, 8]] # a becomes ['A', 'B', 'C', 'D', 'E', [6, 7, 8]] Use << to append elements to the end of an existing array and - to remove array elements a = [] # empty array a << 3 # a becomes [3] ['a', 'b', 'c', 'b', 'a'] - ['b', 'c', 'd'] # results ['a', 'a'] a = [0] * 8 # a becomes [0, 0, 0, 0, 0, 0, 0, 0]
  • 9. Hashes A hash or maps or associative arrays is a data structure that maintains a set of objects known as keys, and associates a value with each key. Hash Initialize numbers = Hash.new or numbers = {} # Create a new, empty, hash object Hash key/value Assignment numbers["one"] = 1 # Map the String "one" to the Fixnum 1 numbers["two"] = 2 # Note that we are using array notation here Or numbers = { "one" => 1, "two" => 2, "three" => 3 } # ruby 1.8 Or numbers = { one: 1, two: 2, three: 3 } # ruby 1.9 Hash value Retrieve sum = numbers["one"] + numbers["two"] # Retrieve values like this Iterate over a hash numbers = { one: 1, two: 2, three: 3 } numbers.each { |key, value| puts “key….. #{key}” puts “value ….#{value}” } Array of Hashes h = [{one: 1}, {two: 2}, {three: 3}]
  • 10. Ranges A Range object represents the values between a start value and an end value. Range Literals: 1..10 # The integers 1 through 10, including 10 1…10 # The integers 1 through 10, excluding 10 Usage: years = 1990..2014 my_birthday = 1998 years.include?(my_birthday) # Returns true string = 'a'..'c‘ string.each { |s| puts s } # prints a b c Note: The Range class defines methods for determining whether an arbitrary value is a member of (i.e., is included in) a range.
  • 11. Symbols In Ruby  Symbols are Strings, just with an important difference –  Symbols are immutable.  A symbol literal is written by prefixing an identifier or string with a colon.  Mutable objects can be changed after assignment while immutable objects can only be overwritten. Symbols interpolation and operations: t = :test # Here t is a symbol s = %s(symbol) # :symbol :”test #{s}” # :”test symbol” Symbol to String Conversion s = “string” s.intern or s.to_sym # converts the string in to symbol :test.to_s or :test.id2name # convers symbol to string
  • 12. Reserved Keywords Reserved word Description BEGIN Code, enclosed in { and }, to run before the program runs. END Code, enclosed in { and }, to run when the program ends. alias Creates an alias for an existing method, operator, or global variable. and Logical operator; same as && except and has lower precedence. begin Begins a code block or group of statements; closes with end. break Terminates a while or until loop or a method inside a block. case Compares an expression with a matching when clause; closes with end. class Defines a class; closes with end. def Defines a method; closes with end. defined? Determines if a variable, method, super method, or block exists. do Begins a block and executes code in that block; closes with end. else Executes if previous conditional, in if, elsif, unless, or when, is not true. elsif Executes if previous conditional, in if or elsif, is not true. end Ends a code block (group of statements) starting with begin, def, do, if, etc. ensure Always executes at block termination; use after last rescue.
  • 13. Reserved Keywords Reserved word Description false Logical or Boolean false, instance of FalseClass. (See true.) for Begins a for loop; used with in. if Executes code block if true. Closes with end. module Defines a module; closes with end. next Jumps before a loop's conditional. nil Empty, uninitialized variable, or invalid, but not the same as zero; object of NilClass. not Logical operator; same as !. or Logical operator; same as || except or has lower precedence. redo Jumps after a loop's conditional. rescue Evaluates an expression after an exception is raised; used before ensure. retry Repeats a method call outside of rescue; jumps to top of block (begin) if inside rescue. return Returns a value from a method or block. May be omitted. self Current object (invoked by a method). super Calls method of the same name in the superclass. The superclass is the parent of this class. then A continuation for if, unless, and when. May be omitted.
  • 14. Reserved Keywords Reserved word Description true Logical or Boolean true, instance of TrueClass. undef Makes a method in current class undefined. unless Executes code block if conditional statement is false. until Executes code block while conditional statement is false. when Starts a clause (one or more) under case. while Executes code while the conditional statement is true. yield Executes the block passed to the method. _ _FILE_ _ Name of current source file. _ _LINE_ _ Number of current line in the current source file.
  • 15. Objects Ruby is a very pure object-oriented language: all values are objects. Object References - When we work with objects in Ruby, we are really working with object references. s = “string” # Create a String object. Store a reference to it in s. t = s # Copy the reference to t. s and t both refer to the same object. Object Lifetime - Ruby uses garbage collection means that Ruby programs are less susceptible to memory leaks than programs written in languages that require objects and memory to be explicitly deallocated and freed. Object lifetime is till then it is reachable. Different operations on Object and object conversion: The equal? Method a = “test” b = c = “test” a.equal?(b) # false : a and b are different objects b.equal?(c) # true The == operator a == b # true Note: equal? Method works like check object_id of two objects and == operators works with the content of the two objects Conversions - to_i, to_s, to_h, to_sym, to_f, to_a Tainted object - When a object has it's tainted flag set, that means, roughly, that the object came from an unreliable source and therefore can't be used in sensitive operations. a = “test”.taint