Ruby Introduction-2

@h6165

Abhishek Yadav

ரூபீ ப்ரோக்ராமர்

Co-organizer: Chennai.rb

Topics covered

  • Array
  • Iterators
  • Hash
  • Class

Array

Array


## Valid arrays:

arr1 = [1, 2, 3]

arr2 = [ 1,
         'A string',
         :my_symbol,
         { a_hash: 42 },
         ->(){ 'lamb-da' } ]

List of similar or dissimilar objects

Array


## Accessing arrays:

arr = [1, 2, 3, 4, 5]

arr[1]   #=> 2
arr[100] #=> nil

## First, last

arr.first  #=> 1
arr.last   #=> 5

## Negative indexes are fine

arr[-1]  #=> 3

Accessed using: []

Array


## Standard Library: 
## Find info about the array:

arr = [1, 2, 3, 4, 5]


arr.size  #  The size  => 5

arr.empty?  # Is it empty? => false

arr.include?(3)  # Does it include 3? => true

The standard library

Array


## Standard Library: Add items

arr = [1, 2, 3, 4, 5]


arr << 6            # Push at the end  => [1,2,3,4,5,6]

arr.push(6)         # Push at the end  => [1,2,3,4,5,6]

arr.unshift(0)      # Push at the start => [0,1,2,3,4,5]

arr.insert(2, 100)  # Insert at an index => [0,1,100,2,3,4,5]


The standard library

Array


## Standard Library: Remove items

arr = [1, 2, 3, 4, 5]


arr.shift          # Remove first one => 1

arr.pop            # Remove last one => 5

arr.delete_at(1)   # Removes the second one => 2


arr = [1, 2, nil, 3, 1]

arr.compact        # Removes nils => [1,2,3,1]

arr.uniq           # Removes duplicates => [1,2,nil,3]

The standard library

Array


## Standard Library: Adding and subtracting

arr1 = [1, 2, 3]
arr2 = [3, 4]


arr1 + arr2  # Simple concatenate => [1,2,3,3,4]

arr1 - arr2  # Elements of arr1 not present in arr2 => [1,2]

arr1 & arr2  # Common elements => [3]


The standard library

Array


## Standard Library: Comparing

arr1 = [1, 2, 3]
arr2 = [3, 4]


arr1 == arr2    #=> false

arr2 == [3, 4]  #=> true

The standard library

Array


## Standard Library: Joining and Slicing

arr = [1, 2, 3, 4, 5]


arr.join      #=> "12345"
arr.join(",") #=> "1,2,3,4,5"


## Slice using range

arr[0..2]   #=> [1,2,3]
arr[1..-1]  #=> [2,3,4,5]


## Slice with size

arr.slice(2, 3)  # At index 2, of size 3 => [3,4,5]

The standard library

Array


## Standard Library: select, reject and count

arr = [1, 2, 3, 4, 5]


arr.select { |x| x >=4 }         #=> [4, 5]

arr.reject { |x| x%2 == 1 }      #=> [2,4]

arr.count { |x| x<3 }            #=> 2



The standard library

Array


## Standard Library: sort and grep

arr = [3, 2, 1, 5, -4]

arr.sort  # => [-4,1,2,3,5]


## We can tell how to sort

arr.sort_by { |x| x**2 }  # => [1,2,3,-4,5]


## Search on elements

arr.methods.grep /sort/  #=> /All containing 'sort'

The standard library

Array


## Standard Library: permutations and combinations

arr = [1, 2, 3]


arr.permutation.to_a        #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

arr.combination(3).to_a     #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]

arr.product([4,5])          #=> [[1,4],[1,5],[2,4],[2,5],[3,4],[3,5]]



The standard library

Array


## Standard Library: sample and shuffle

arr = [1, 2, 3]

arr.sample      # Gets a random element => 2
arr.sample(2)   # A random sub-array of size 2 => [1,3]


arr.shuffle     # Shuffles it => [2,1,3]

The standard library

Array


## Standard Library: iterators and map/reduce

## Next section ->

The standard library

Iterators

Iterators

How we loop in Ruby

  • loop
  • while
  • for..in
  • Iterators

Iterators are more popular than the others

Iterators


## while loop


i = 1
while i <= 3 do
  puts i**2
  i += 1
end

Loops: for, while, loop

Iterators

## for..in loop

for i in [1,2,3]
  puts i ** 2
end

Loops: for, while, loop

Iterators

## loop

i = 1
loop {
  puts i ** 2
  i += 1
  break if i > 3
}


## An infinite loop

loop { print rand }

Loops: for, while, loop

Iterators

## each


[1,2,3].each { |x| puts x ** 2 }


## or 

arr = [1, 2, 3]
arr.each do |x|
  puts x **2
end

each

Iterators


[1,2,3].each { |x| puts x ** 2 }

each

  • Every element of the array is passed to the block as x
  • The block is executed  for every value passed as x
[1,2,3] array
each iterator method
{ |x| puts x ** 2} code block

Iterators

each

  • Iterators are idiomatic Ruby
  • They read better
  • They can be redefined

Iterators


[1,2,3].each { |x| puts x ** 2 } ##=> Prints 1, 4, 9, returns [1,2,3]

[1,2,3].map { |x| x ** 2 }       ## => [1,4,9] 

map

Similar to each, but returns the result of evaluation each time

Hash

Hash

marks = {
 "Ross"     => 90,
 "Monica"   => 91,
 "Chandler" => 85,
 "Joey"     => 60,
 "Pheobe"   => 70,
 "Rachel"   => 85
}


marks["Joey"]    # => 60
marls["Gunther"] # => nil
  • Is the data structure for holding key-value pairs
  • Is part of the default Ruby setup

Hash

h = { 'a': 1, 'b': 2 }

h['a']      #=> 1
h['b']      #=> 2
h['c']      #=> nil


h['c'] = 3
h['c']      #=> 3


h['b'] = 4
h['b']      #=> 4

More examples

Hash

## Count the number of times a value occurs in a list


def foo(list, num)
  h = {}
  list.each do |x|
    h[x] = 0 if h[x] == nil
    h[x] += 1
  end
  h[num]
end

list = [1, 2, 100, 50, 60, 24, 50, 23, 50, 50]

foo list, 50  # => 4

Hash simplifies code for many common programming problems

Class

Class

  • Ruby is a class-based object orient programming language

 

  • Class is like a pre-definition of what the object will look like, what data it can hold, and what actions it can perform

 

  • An object is an instance of a class -  many objects can be created for a class

Class

In practice, this means entities (variables, literals) in our program will act some-what like this:

object.method(argument)

And the Class is where the method is defined

Class


## Object and method

arr = [1, 2, 3]

arr.first    #=> object: arr   method: first
arr.push(4)  #=> object: arr   method: push    argument: 4


## And even:

arr[2]       #=> object: arr   method: []      argument: 2

Class


## Define the class with a method
class A

  def foo(num)
    num**2
  end

end


a = A.new    # create an instance of class A using 'new'
a.foo(10)    # Call the foo method



a.class      #=> A

Our own class

Thanks

@h6165

ceg-0316-ruby-intro

By Abhishek Yadav

ceg-0316-ruby-intro

  • 1,078