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.
#!/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
Use self as setting/getting attributes inside class definition
Use self to denote a method within the class definition as a class method
use self to referece the calling object within an instance method definition