Лекция Ruby
Лекция Ruby
● Numbers
● Text
● 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.
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
String interpolation:
“Pi value in Ruby #{Math::PI}” # pi value in ruby 3.141592…
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:
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 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
Hash Initialize
numbers = Hash.new or numbers = {} # Create a new, empty, hash object
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.
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.
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