Reputation: 487
I have the following class:
class Foo
def [](*files)
end
def read(file)
end
end
And I want to call the function read like this:
bar = Foo.new
bar['todo.txt'].read
Is there a way to make this syntax possible?
Upvotes: 2
Views: 76
Reputation: 14082
Use instance variable to share context among instance methods.
class Foo
def [](*files)
@files = files
self
end
def read(file = nil)
if file
File.read(file)
else
@files.map{|file| File.read(file)}.join
end
end
end
Upvotes: 2
Reputation: 11895
If you want to be able to chain those methods, I believe you will have to return self
from []
.
class Foo
attr_accessor :files
def [](*files)
@files = files
self
end
def read
p @files
end
end
Upvotes: 2