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).
class Object
attr_accessor :str
def initialize(sent)
@str = sent
end
end
class Solution
attr_accessor :array
def initialize
@array = []
end
def make_Array
File.open("test.txt").each do | line |
@array << Object.new(line.chomp)
end
print @array
end
end
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.
class Solution
attr_accessor :array
def initialize
@array = []
end
def make_Array(data_file)
File.open(data_file).each do | line |
@array << line.chomp
end
print @array
end
end
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?