1

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]
    ....

4 Answers 4

10

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
Sign up to request clarification or add additional context in comments.

1 Comment

+1, I usually use the underscore version. But then one should also wonder if row should be a hash with descriptive key names...
6

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

Comments

2

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

Comments

1

If you don't mind doing some meta-programming (just keeps all names and indices together in one place):

{:name => 2, :description => 3, :status => 5}.each do |name, i| 
  instance_variable_set("@#{name}", row[i]) 
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.