我正在尝试将我制作的 Java 程序重新编程为 Ruby,以帮助我学习这门语言。但是,我在寻找用 Ruby 编写 Java 代码的这个特定部分的方法时遇到了很多麻烦:
/* 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);
}
此代码采用一个文件,该文件包含两列中的整数列表(第一列是磅,第二列是盎司),如下所示:
120 2
195 15
200 5
112 11
252 0
140 9
,并使用每行中的数字制作一堆 Weight 对象。然后它将它们添加到列表中。在 Ruby 中有一种简单的方法可以做到这一点吗?到目前为止,这是我的 Ruby 程序的样子:
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)
感谢您的帮助!
最佳答案
不像你问的那样,但由于 ruby 是一种动态语言,我认为没有必要这样想。所以这里是你如何做到的
while (line = infile.gets)
pounds, ounces = line.split(' ')
p "-#{pounds}- -#{ounces}-"
end
输出
-120- -2-
-195- -15-
-200- -5-
-112- -11-
-252- -0-
-140- -9-
或者更像 ruby 的方式(我认为)
File.open(in_file_name, "r").each_line do |line|
pounds, ounces = line.split(' ')
p "-#{pounds}- -#{ounces}-"
end
关于java - 是否有相当于 Java 的 "next[type]"扫描器的 ruby ?具体来说,一个停止照顾该类型的第一个实例的人?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10290958/