Power of Eloquence

When saying “Hello World!” isn’t enough anymore

Understanding Ruby Self (Part 2)

| Comments

From my previous post, I discussed the purpose of using self in Ruby and how Ruby object’s scope will change in any given point of its running time. Here I’m writing to illustrate the examples further.

Supposed we have a hypothetical anti-virus scanning software we’re building. The anti-virus software will have the following preventative features that will keep your computer safe from Internet viruses.

And thus to define this class in Ruby, we do the following.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/ruby

class VirusScanner
    attr_accessor: list_of_known_viruses
    attr_accessor: list_of_files

    def update(new_list_of_viruses)
        list_of_known_viruses = new_list_of_viruses
    end

    def print_virus_list
        puts list_of_known_viruses
    end

    def scan(directory_to_scan)

        list_of_files = Dir[File.join(directory_to_scan, '**', '*')].reject{|p| File.directory? p}

        while(list_of_files) do |each_file|
            check_for_virus(each_file)
        end
    end

    def check_for_virus(file)
       for a_virus in list_of_known_viruses do
          a_virus
          file.ftype(a)=="file"
       end
    end

end

virusscanner = VirusScanner.new
  1. Use self as setting/getting attributes inside class definition

  2. Use self to denote a method within the class definition as a class method

  3. use self to referece the calling object within an instance method definition

Comments