I am trying to reprogram a Java program that I made into Ruby, to help me learn the language. However, I'm having a lot of trouble finding a way to code this particular section of Java code in Ruby:
/* read the data from the input file and store the weights in the
array list */
Scanner readFile = new Scanner(new FileReader(inFileName));
ArrayList<Weight> listOfWeights = new ArrayList<Weight>();
while (readFile.hasNext()) {
int pounds = readFile.nextInt();
int ounces = readFile.nextInt();
Weight thisWeight = new Weight(pounds, ounces);
listOfWeights.add(thisWeight);
}
This code takes a file that has a list of integers in two columns (the first being pounds and the second being ounces) like this:
120 2
195 15
200 5
112 11
252 0
140 9
, and makes a bunch of Weight objects using the numbers in each row. Then it adds them to a list. Is there an easy way to do this in Ruby? Here's what my Ruby program looks like so far:
begin
puts "Enter the name of the input file > "
in_file_name = gets
puts \n
list_of_weights = []
File.open(in_file_name, "r") do |infile|
while (line = infile.gets)
Thanks for the help!
Not equivalent as you asked but since ruby is a dynamic language I think there is no need for such think. So here is how you could do it
while (line = infile.gets)
pounds, ounces = line.split(' ')
p "-#{pounds}- -#{ounces}-"
end
output
-120- -2-
-195- -15-
-200- -5-
-112- -11-
-252- -0-
-140- -9-
Or a more ruby way (I think)
File.open(in_file_name, "r").each_line do |line|
pounds, ounces = line.split(' ')
p "-#{pounds}- -#{ounces}-"
end