2

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!

1 Answers1

1

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
Ismael Abreu
  • 16,443
  • 6
  • 61
  • 75
  • 3
    `split` splits on whitespace by default and a bit of `to_i` (or `Integer()` if you want exceptions) would be a good idea as well: `pounds, ounces = line.split.map(&:to_i)`. – mu is too short Apr 24 '12 at 02:55
  • @muistooshort didn't knew about that about split, but it makes sense. And nice way to do to_i using map. – Ismael Abreu Apr 24 '12 at 03:14
  • Thanks, it worked great. I ended up using your second solution and using mu is too short's advice. Everything is working smoothly now (except that pesky `gets` function..) – Taylor Lapeyre Apr 24 '12 at 04:46