小编Chr*_*ris的帖子

ruby 1.9如何将数组转换为不带括号的字符串

我的问题是如何在没有得到括号和引号的情况下将数组元素转换为ruby 1.9中的字符串.我有一个数组(数据库提取),我想用它来创建一个定期报告.

myArray = ["Apple", "Pear", "Banana", "2", "15", "12"]
Run Code Online (Sandbox Code Playgroud)

在ruby 1.8中,我有以下几行

reportStr = "In the first quarter we sold " + myArray[3].to_s + " " + myArray[0].to_s + "(s)."
puts reportStr
Run Code Online (Sandbox Code Playgroud)

这产生了(想要的)输出

在第一季度,我们卖出了2个Apple.

红宝石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
Run Code Online (Sandbox Code Playgroud)

返回运行时错误

/home/test/example.rb:450:in`+':无法将Array转换为String(TypeError)

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

tempStr0 = myArray[0].to_s
myLength = tempStr0.length
tempStr0 = tempStr0[2..myLength-3]
tempStr3 = myArray[3].to_s
myLength = tempStr3.length …
Run Code Online (Sandbox Code Playgroud)

ruby arrays string version string-interpolation

13
推荐指数
2
解决办法
3万
查看次数

标签 统计

arrays ×1

ruby ×1

string ×1

string-interpolation ×1

version ×1