2014-09-04 119 views
-2

我有一个名为quotes.txt的八行文件。当我运行下面的代码时,它输出一个包含8个项目并且长度为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 
+0

,请复制粘贴输出'的提出quotations' – Josh 2014-09-04 00:46:56

回答

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 
+0

由于代码和输出的OP显示,我不知道为什么阵列报告的元素1,当它看起来有多个元素时。 – MxyL 2014-09-04 01:01:35

+1

@MxyL我粘贴了检查的输出。它是一个包含**一个**字符串的数组,其中包含一个字符串数组;因此,大小为1. – Josh 2014-09-04 01:05:28

+1

这很有趣,因为OP的输出是包含多个字符串的数组。看起来'puts'函数似乎造成了这种混淆,并使调试变得困难。 – MxyL 2014-09-04 01:08:13