This was part of a larger project and I’ve successfully passed all the test cases, but I’m still having trouble understanding the concept of reading from a text file (line by line), creating a class instance for each read line (done inside a different class), and putting each of those class instances into an array (the array is an instance variable inside of the second class).
@str = sent
@array = 
File.open("test.txt").each do | line |
@array << Object.new(line.chomp)
My text file (names “test.txt”) is as follows:
This is a really really really cool experiment really
Cute little experiment
Will it work maybe it will work do you think it will it will
Upon running the code, I get this message:
warning: redefining Object#initialize may cause infinite loop
Aren’t I creating unique instances of the class when I read each line of the file, so doesn’t that mean that I can shovel them into the array instance variable? Note: the prompt specified that I should only have these two classes in my solution!
Why are you creating an Object class? Isn’t that provided by Ruby?
Hint: If Ruby has an Object class which is the base class of all objects and you provide an Object class…
Are you trying to monkey patch the constructor in Object?
If you are reading a string. Why don’t you save the string in the array? Why wrap the String in another object? I guess I just don’t see any advantage to wrapping a string in another object.
Why not have something like below?
@array = 
File.open(data_file).each do | line |
@array << line.chomp
Hm, so this was what the prompt said:
The specifics of the analyzers instance variable to be held in the Solution class:
• array - an array that will hold an Object for each line of the input text file
The specifics for the make_Array() method:
Implement the make_Array() method to:
• Read the ‘test.txt’ file in lines
• Create an array of Objects for each line in the file
So when they say to “Create an array of Objects…”, they’re not saying to create new instances of the Object? If I just pass the line of the file into the array instance variable, how will the program know that the array is an array of Objects and not just plain strings?
A string is an object.
If you open the irb and type String.ancestors you’ll get:
=> [String, Comparable, Object, Kernel, BasicObject]
If you need to call Object methods on the array elements then it’ll work if you use a string because a String is an Object.