Intermingling Attr_Accessor and an Initialize Method in One Class

Intermingling attr_accessor and an initialize method in one class

initialize and attr_accessor have nothing to do with each other. attr_accessor :name creates a couple of methods:

def name
@name
end

def name=(val)
@name = val
end

If you want to set name upon object creation, you can do it in the initializer:

def initialize(name)
@name = name
# or
# self.name = name
end

But you don't have to do that. You can set name later, after creation.

p = Person.new
p.name = "David"
puts p.name # >> "David"

Alternative initialize for a Class to avoid processing already known information

You are creating an instance variable @drop_entry in your class method from_entry and obviously it wont be available to your object that you are creating in this method. One workaround is to pass it as a parameter when you are initializing the class. It should work if you do the following modifications:

  1. In your from_entry class method change

    self.initialize(@drop_entry) 

    to

    new(@drop_entry)
  2. Modify initialize method to:

    def initialize(drop_entry)
    @drop_entry = drop_entry
    @path = @drop_entry.path
    end

Or if your class is tied up to pass only the path parameter, ie. you dont want to change the other existing code then you can use an optional parameter drop entry like so

    def initialize(path, drop_entry=nil)

How to Initialize Class Arrays in Ruby

You need to use initialize as a constructor as below code and is there any reason why not to use initialize/constructor. And please fix a typo error in class definition Class Something to class Something no camel case or first letter capitalize while in class

class Something 
def initialize
@something = Array.new
end
def dosomething
s = 5
@something << s
end
end

class variable @@ are available to the whole class scope. so they are working in the code and if you want to use instance variable @ you need to initialize it as above. The instance variable is share with instance/objects of a class

for more details visit the link Ruby initialize method



Related Topics



Leave a reply



Submit