Ruby长度不显示数组的正确长度

时间:2014-09-04 00:44:38

标签: ruby

我有一个包含八行的文件,名为quotes.txt。当我运行以下代码时,它输出一个包含八个项目且长度为1的数组。

我期待8而不是1.我在这里做错了什么?

#!/usr/bin/env ruby
# myrandom_sig.rb

filename = ARGV[0] || (ENV['HOME'] + '/Documents/rubybyexample/RBE_scripts/quotes.txt')
quotation_file = File.new(filename, 'r')
file_lines = quotation_file.readlines()
quotation_file.close()
quotations     = file_lines.to_s.split("\n\n")
puts quotations
puts quotations.length

输出

➜  RBE_scripts  ruby -w myrandom_sig.rb quotes.txt 
["It is better to
have loved and lost than just to have lost.\n", "It is bad luck to be
superstitious.\n", "If it jams, force it. If it breaks, it needed
replacement anyway.\n", "Always remember that you are unique. Just
like everyone else.\n", "A woman without a man is like a fish without
a bicycle.\n", "A bachelor is a guy who is footloose and fiancee
free.\n", "If Yoda a great Jedi master he is, why not a good sentence
construct can he?\n", "People will remember you better if you always
wear the same outfit.\n"] 
1

1 个答案:

答案 0 :(得分:2)

这是quotations.inspect

的输出
["[\"Test\\n\", \"Line 2\\n\", \"Line 3 and some \\n\"]"]

问题源于你致电file_lines.to_s.split("\n\n")。您正在将数组强制转换为字符串,然后返回到数组。

这是你想做的事情:

filename = ARGV[0] || (ENV['HOME'] + '/Documents/rubybyexample/RBE_scripts/quotes.txt')
quotation_file = File.new(filename, 'r')
quotations = quotation_file.readlines()
quotation_file.close()
puts quotations.size