Ruby Basics – Part I – Booleans



Ruby Basics – Part I – Booleans

0 0


ruby_basics_presentation


On Github vlasiak / ruby_basics_presentation

Ruby Basics

Part I

Quick lecture overview

  • Data Types
  • Expressions
  • Operators
  • Methods

Data Types

  • Booleans
  • Numbers
  • Strings
  • Symbols
  • Arrays
  • Ranges
  • Hashes
  • Nil

Booleans

Boolean data type - type of data, intended to represent the only 2 options: 'True' and 'False'. Mostly used inside the conditional statements.

true.class => TrueClass
false.class => FalseClass

'Ruby awesome' if true => "Ruby awesome"
'Ruby sucks' if false => nil

Try to guess

true    ? 'true' : 'false'
false   ? 'true' : 'false'
nil     ? 'true' : 'false'
1       ? 'true' : 'false'
0       ? 'true' : 'false'
'false' ? 'true' : 'false'
''      ? 'true' : 'false'
[]      ? 'true' : 'false'

Numbers

Numeric Class methods

Integer

Integer numbers is simply a sequence of digits. Fixnum numbers are integers up to a certain limit. The limit is machine dependent. Bignum values hold integers outside the range of the Fixnum. If any operation on a Fixnum exceeds its range, the value is automatically converted to a Bignum.

0.zero? => true
7.next => 8
-5 + 7 => 2
5 / 2 => 2

1000.class => Fixnum
1_000_000_000_000.class => Bignum
Integer Class methods * Fixnum Class methods * Bignum Class methods

Float

Floating point numbers represent real numbers. Complex, Big Decimal and Rational classes are not built-in to Ruby, but are distributet with Ruby as part of the standart library.

5.8.integer? => false
7.1 - 2 => 5.1
3 - 1.5 => 1.5
5.0 / 2 => 2.5

(5.0 / 2).class => Float
Float Class methods * Big Decimal Class methods

Strings

A string is a data type representing textual data (sequence of unicode characters). Double quoted strings allow interpolation.

'Ruby'.class => String
'ruby'.capitalize => "Ruby"
'RubY'.downcase => "ruby"

"The time is #{Time.now}" => "The time is 2016-04-16 20:24:35 +0300"
'The time is #{Time.now}' => "The time is \#{Time.now}"
'The time is ' + Time.now.to_s => "The time is 2016-04-16 20:24:35 +0300"
'The time is '.concat(Time.now.to_s) => "The time is 2016-04-16 20:24:35 +0300"
String Class methods

Symbols

Symbols are simply constant names that you don’t have to predeclare and that are guaranteed to be unique. A symbol literal starts with a colon and is normally followed by some kind of name.Symbols are frequently used as keys in hashes.

:ruby.class => Symbol
'ruby'.to_sym => :ruby

'Ruby basics lecture' if current_lecture == :ruby_basics => "Ruby basics lecture"

:ruby.object_id == :ruby.object_id => true
'ruby'.object_id == 'ruby'.object_id => false
Symbol Class methods

Arrays

Array is an indexed collection of elements, accessible using a key. The key is an integer and starts with 0 index.

[1, 2, 3].class = Array

array = [1, 'second', true, 4, 5] = > [1, 'second', true, 4, 5]
array[0] => 1
array.last => 5
array[-2] => 4
array[2, 2] => [true, 4]
[1, 2, 'str', 5].map{ |element| element * 2 } => [2, 4, "strstr", 10]
Array Class methods

Ranges

A Range represents an interval — a set of values with a beginning and an end.

(1..10).class => Range

(1..10).include?(5) => true
(-5..-1).to_a => [-5, -4, -3, -2, -1]
('a'...'d').each_with_index { |n, i| print "#{i}: #{n}, " } => "0: a, 1: b, 2: c"
Range Class methods

Hashes

A Hash (associative array, map, or dictionary) is a collection of key-value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index.

person = { name: 'Vasyl', age: 22, address: 'Lviv city' }
person.class => Hash
person[:name] => "Vasyl"
person[:age] => 22
person[:gender] => nil

person = { 'name' => 'Vasyl', 'age' => 22, 'address' => 'Lviv city' }
person.class => Hash
person[:name] => nil
person['name'] => "Vasyl"
...
Hash Class methods

Nil

Nil is an object to represent nothing. Could be interpreted as false inside the conditional statements.

nil.class => NilClass

nil.nil? => true
nil.to_a => []
nil.to_i => 0

Listened carefully? Love bonuses?

Simply find proper methods for ...

1.234567 => 1.23 'a' => 'b' 'vasyl' => 'VASYL' 'vasyl' => 'Vasyl' 'vasyl' => 'lysav' :vasyl => 5 :vasyl => 'vasyl' [1, 2, 3, 4] => 1 [1, 2, 3, 4] => 4 [1, 2, nil, 3, nil] => [1, 2, 3] [1, 2, 3, 4] => [4, 3, 2, 1] [1, 2, 3, 4] => [0, 1, 2, 3, 4] { a: 1, b: 2, c: 3} => [:a, :b, :c] { a: 1, b: 2, c: 3} => [1, 2, 3]

Other "Type-like" Classes

Time Class methodsDateTime Class methods
Time.now => "2016-04-16 23:01:04 +0300"
...
Date Class methods
Date.parse('12/01/2016').month => 1
...
Regexp Class methods
/http/ =~ 'http://www.vk.com' => 0
...

Duct Typing

In Ruby we don’t declare the types of variables or methods — everything is just some kind of object. In Ruby, the class isn't always the same as the type. Instead, the type of an object is defined more by what that object can do. It is called duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck.

def save_name(name, target)
    target << name
end

array = []
string = ''

save_name('Vasyl', array) => ["Vasyl"]
save_name('Vasyl', string) => "Vasyl"

Expressions

Variables

Variables are the memory locations which hold any data to be used. Each variable holds a reference to an object. A name is an uppercase letter, lowercase letter, or an underscore ("_"), followed by Name characters (any combination of upper- and lowercase letters, underscore and digits). You couldn't use any reserved in Ruby words for determining the name of the variable.

local_variable = 'local variable'
CONSTANT = 'constant'
$global_variable = 'global variable'
@instance_variable = 'instance variable'
@@class_variable = 'class variable'

person1 = 'Tim'
person2 = person1
person1[0] = 'J'

person1 => "Jim"
person2 => "Jim"

Reserved words

Expressions

One of the first differences with Ruby is that anything that can reasonably return a value does: just about everything is an expression. For example, the if and case statements both return the value of the last expression executed. Methods have the same behavior. In Ruby, many operators are actually method calls.

a = b = c = 0 => 0
(a.*(b)).+(c) <=> a * b + c
a, b, c = 1, 2, 3
a, b = b, a
a, b = 1, 2, 3, 4 => a=1, b=2

Assignment operators

Assignment operator is the operator used for assignment.

+=   -=   *=   /=   =   %=   &=   |=   ^=   <<=   >>= &&= ||= **=

No post- pre increment!

Arithmetic operators

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

+ - * / % **

Comparison operators

Comparison operators are used in logical statements to determine equality or difference between variables or values.

== != > < <= >= <=> === .eql? .equal?

Logical operators

Logical operators are used to determine the logic between variables or values.

and or not && || !

Bitwise operators

Bitwise operator works on bits and perform bit by bit operation.

& | ^ ~ << >>

Precedence (high to low)

Explain the difference

result = true and false
result = true && false

Operators overloading

class Fixnum
    alias old_plus +

    def +(other)
        old_plus(other).succ
    end
end

1 + 2 => 4

Methods

Method is defined using the keyword def. Method names should begin with a lowercase letter or underscore, followed by letters, digits, and underscore. A method always returns a value and its name may end with one of ?, !, or =. Method definition:

def my_method(arg1, arg2='default') # 2 arguments, but 2nd already has a default value
    # Code for the method would be here
end

Method invoking:

1. my_method('first_param', 'second_param')
2. my_method('first_param')

Why do we need methods?

  • They allow us to conceive of our program as a bunch of sub-steps. (Each sub-step can be its own method. When any program seems too hard, just break the overall program into sub-steps!);
  • They allow us to reuse code instead of rewriting it;
  • Methods allow us to keep our variable namespace clean (local variables only "live" as long as the methods does);
  • Methods allow us to test small parts of our program in isolation from the rest. This is especially true in interpreted langaues, such as Ruby.

Steps to Writing a Method

  • Understand the purpose of the method;
  • Define the data that comes into the function from the caller (in the form of parameters);
  • Define what data variables are needed inside the method to accomplish its goal;
  • Decide on the set of steps that the program will use to accomplish this goal (the algorithm).

Recursion

Classic example

A recursive methos is a method that calls itself. It can be used to replace cycle.

def fact(n)
    return 1 if n.zero?
    n * fact(n-1)
end

fact(5) => 120

What next?

  • Control structures (if, unless, switch)
  • Loops & Iterators
  • Ruby Style Guide
No questions? No answers!

Created by Vasyl Lasiak / @vlasiak

1
Ruby Basics Part I