如何在Ruby 1.9中将数组转换为字符串而不带括号

15
我想问如何在 Ruby 1.9 中将数组元素转换为字符串,而不会得到方括号和引号。我有一个数组(DB 提取),我希望使用它来创建定期报告。
myArray = ["Apple", "Pear", "Banana", "2", "15", "12"]
在 Ruby 1.8 中,我有以下这行代码。
reportStr = "In the first quarter we sold " + myArray[3].to_s + " " + myArray[0].to_s + "(s)."
puts reportStr

产生了(所需的)输出

在第一季度,我们销售了2个苹果。

在ruby 1.9中相同的两行代码产生了(不需要的)输出

在第一季度,我们销售["2"] ["Apple"](s)。

阅读文档后, Ruby 1.9.3 doc#Array#slice 我认为我可以写出这样的代码:

reportStr = "In the first quarter we sold " + myArray[3] + " " + myArray[0] + "(s)."
puts reportStr

会返回运行时错误

/home/test/example.rb:450:in `+': 无法将数组转换为字符串 (TypeError)

我的当前解决方案是使用临时字符串删除括号和引号,例如:

tempStr0 = myArray[0].to_s
myLength = tempStr0.length
tempStr0 = tempStr0[2..myLength-3]
tempStr3 = myArray[3].to_s
myLength = tempStr3.length
tempStr3 = tempStr3[2..myLength-3]
reportStr = "In the first quarter we sold " + tempStr3 + " " + tempStr0 + "(s)."
puts reportStr

总的来说,它有效。

然而,有没有更加优雅的“Ruby”方法来做到这一点呢?


周三,10月23日18:16:46#8>ruby -v ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-darwin12.5.0]周三,10月23日18:16:51#9>irbirb(main):001:0> myArray = ["苹果", "梨子", "香蕉", "2", "15", "12"] => ["苹果", "梨子", "香蕉", "2", "15", "12"]irb(main):002:0> reportStr = "在第一季度,我们卖出了" + myArray[3].to_s + "个" + myArray[0].to_s + "。" => "在第一季度,我们卖出了2个苹果。"irb(main):003:0> puts reportStr 在第一季度,我们卖出了2个苹果。我认为你的问题与Ruby版本无关。 - Leif
抱歉 Leif,但是你的评论对我没有帮助。 - Chris
我没有发布答案,因为我无法在1.9下重现您的问题 - 因此只能发表评论。我认为你不会喜欢“对我有效”的答案。 - Leif
4个回答

43
你可以使用.join方法。

例如:

my_array = ["Apple", "Pear", "Banana"]

my_array.join(', ') # returns string separating array elements with arg to `join`

=> Apple, Pear, Banana

3

使用插值代替字符串拼接:

reportStr = "In the first quarter we sold #{myArray[3]} #{myArray[0]}(s)."

它更符合惯用语,更高效,需要打字更少,并且会自动调用to_s


1
如果您需要对多种水果执行此操作,最好的方法是转换数组,然后使用each语句。
myArray = ["Apple", "Pear", "Banana", "2", "1", "12"]
num_of_products = 3

tranformed = myArray.each_slice(num_of_products).to_a.transpose
p tranformed #=> [["Apple", "2"], ["Pear", "1"], ["Banana", "12"]]

tranformed.each do |fruit, amount|
  puts "In the first quarter we sold #{amount} #{fruit}#{amount=='1' ? '':'s'}."
end 

#=>
#In the first quarter we sold 2 Apples.
#In the first quarter we sold 1 Pear.
#In the first quarter we sold 12 Bananas.

1
你可以将其看作是arrayToString() array = array * " "

E.g.,

myArray = ["One.","_1_?! Really?!","Yes!"]

=> "One.","_1_?! Really?!","Yes!"

myArray = myArray * " "

=> "One. _1_?! Really?! Yes."


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接