2014-09-04 114 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