我的问题是关于如何在没有括号和引号的情况下在 ruby 1.9 中将数组元素转换为字符串。我有一个数组(数据库提取),我想用它来创建定期报告。
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
产生(想要的)输出
In the first quarter we sold 2 Apple(s).
ruby 1.9 中相同的两行产生(不需要)
In the first quarter we sold ["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 `+': can't convert Array into String (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”方式可以做到这一点?
最佳答案
您可以使用 .join
方法。
例如:
my_array = ["Apple", "Pear", "Banana"]
my_array.join(', ') # returns string separating array elements with arg to `join`
=> Apple, Pear, Banana
关于ruby 1.9 如何将数组转换为不带括号的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19534973/