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:
In your
from_entry
class method changeself.initialize(@drop_entry)
to
new(@drop_entry)
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
New to Ruby and Am Having Trouble with Load_Path
Disabling Flash Message Without Disabling Cache on Click on Back Button in Rails
Ruby Executable Won't Start on Win10 and Win7
Seahorse::Client::Networkingerror Amazon S3 File Upload with Rails
Sublime Text 2 Doesn't Save Built SASS File
How to Make an Infowindow Automatically Display as Open with Google-Maps-For-Rails
How to Overwrite the '{ }' Object
How to Return the Number of Devise Users Currently Logged In
What Is the Fully Qualified Name of a Model in Ruby on Rails
Loaderror - Cannot Open Shared Object File - File Is Present, But It Says No Such File
Why Sinatra Request Takes Em Thread
One Line If Statement Not Working
What Is the Path to Learn Bdd on Ruby on Rails
Check If a Table Exists in Rails