Thursday, 15 January 2015

How to add an object into another class? (Ruby) -



How to add an object into another class? (Ruby) -

i have ana assignment(which means have quite strict methods use).

so have class file simulates file. - conatains either nil or single string, or single symbol, or single number or single boolean (true/false). have method initializes file, have method data_type determines type (#class) of contents of file, getter/setter, etc..

i have class dictionary may contain other directories , files. should have next methods within of it:

add_file(name, file) - adds file named name. file should object of class file have no need check whether input object belongs class.

add_directory(name, directory) - adds directory name name. directory object of class directory. may missed, in case empty directory created.

etc.. etc..

i have done of class file methods have problem making 2 methods mention in class directory. have lot of similarities comment on add_file(name, file) 1 should enough.

all think of name = file.new not not work leaves out file thing have totally no thought is.

def add_file(name, file) name = file.new @name = name end

this is, of course, highly wrong think of.

all help appreciated. give thanks you! , i'm sorry asking silly questions.

and remember, simulation only! files aren't actual files. file random name fits. highly uncertainty should require anything!

edit: friend of mine mentioned file exists. might have match name. however.. i'm still highly confused.

edit2: in lines of @files[name] = file @files beingness hash?

you might want alter class file different name there file class.

any way i'm guessing that works this:

ok, re-read op , realised dictionary typo , redid code resembles:

class directory attr_accessor :name,:store def initialize name self.name = name self.store = {} end def add_file(file) self.store[file.name] = file end def add_directory(directory) self.store[directory.name] = directory end def [](name) self.store[name] end end class file attr_accessor :name, :content, :data_type def initialize name,content = nil,data_type = nil self.content = content self.name = name self.data_type = data_type || content.class end end

then can do

file1 = file.new('hw.rb','puts "hello world!"', 'ruby file') file2 = file.new('gbw.rb','puts "good bye world!"', 'ruby file') root = directory.new('root') rb = directory.new('rb') rb.add_file(file1) root.add_file(file2) root.add_directory(rb) puts root['rb']['hw.rb'].content

and if used splat operator argument in add_file , add_directory methods itterate through argument , add together each file utilize like

file1 = file.new('hw.rb','puts "hello world!"', 'ruby file') file2 = file.new('gbw.rb','puts "good bye world!"', 'ruby file') root = directory.new('root') root.add_file(file1,file2)

research 'ruby splat operator arguments' info on mean

ruby class object

No comments:

Post a Comment