Answer the question
In order to leave comments, you need to log in
Self or @ for a class attribute?
Good day!
On the current issues, a lot of articles were read and the whole Google was searched, along with the Ruby Way, but specifically I did not understand what was happening.
The question is:
Is it right or wrong to use self in the initialize method for class attributes?
And would it be a violation if, say, we put "@" in front of attributes, and not self?
Judging by everything studied and read, I conclude that you need to set self, because we are calling the method, and not accessing the variable itself. Accordingly, "@" must be used when referring to a variable as a getter, and not as a setter.
Please judge.
Thank you in advance!
class Log_parse
attr_accessor :dir, :input_filename, :output_filename, :result_filename,
:src_ip_final_table, :dst_ip_final_table,
:proto_final_table, :service_port_final_table
def initialize
self.dir = ""
self.output_filename = []
self.input_filename =
[
'01_02_2019.txt', '05_02_2019.txt',
'07_02_2019.txt', '09_02_2019.txt',
'11_02_2019.txt', '13_02_2019.txt',
'15_02_2019.txt', '18_02_2019.txt',
'20_02_2019.txt', '21_02_2019.txt',
'24_02_2019.txt', '26_02_2019.txt',
'28_02_2019.txt'
]
@input_filename.each_with_index do |filename, iterator|
self.output_filename[iterator] = @dir + 'output_' + filename
end
self.src_ip_final_table = []
self.dst_ip_final_table = []
self.proto_final_table = []
self.service_port_final_table = []
end
# ...
end
Answer the question
In order to leave comments, you need to log in
This is the same. self.dir =
calls the dir=
one you created when you specified attr_accessor :dir
it, it looks something like this:
def dir=(str)
@dir = str
end
@
, also 4 characters shorter =) @
, you can use it without attr_accessor
. But if you need a getter and setter, then it's better to use attr_accessor
than to write them yourself, because your code will be in Ruby, but attr_accessor
written in C.
Your simple question is not as simple as it seems.
The downside of instance variables is that they default to nil, so it's possible to miss a typo. Many come to this, because sooner or later they write code in which the value nil is allowed for an instance variable, and it is always nil there due to a typo. Instance variables are good for memoization, but their use is best kept to a minimum.
In this case, there is no ideal solution, because you cannot declare a private setter in ruby.
Those. in the following code
class Log_parse
attr_accessor :dir
def initialize
self.dir = ""
end
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question