我想问如何在 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”方法来做到这一点呢?