I am just wondering if there is any best way to initialize the class instance from array:
def initialize(row)
@name = row[2]
@description = row[3]
@status = row[5]
....
I am usually using the following style:
def initialize row
@name, @description, @status = *row
end
If you need to ignore some arguments you can do the following:
ignored, ignored, @name, @description, ignored, @status = *row
Or shorter:
_, _, @name, @description, _, @status = *row
row should be a hash with descriptive key names...If you have to work with data like
row = [ 0, 1, 'Smith', 'red nose', 3, 'awake']
and you have to go by the position of the fields, then your code is OK. You could shorten it like this:
def initialize (row)
@name, @description, @status = row.values_at(2,3,5) # things like (5,2,3) are allowed.
end
in my opinion you should not use such style of initialization because it is very error-prone
class interface must be explicit and visible from first glance so instead of
def method(array_of_attributes)
stick to
def method(meaningful_name_1, meaningful_name_2, options={})
as it is then much easier to see what method expects from both auto-generated docs and from looking at method definition
also there is nothing wrong with passing array of attributes to a method if that is essential for you:
def method_one
arguments_for_method_two = [name, description, status]
method_two(*arguments_for_method_two)
end
def method_two(name, description, status)
# blah ...
end