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