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

Chr*_*ris 13 ruby arrays string version string-interpolation

我的问题是如何在没有得到括号和引号的情况下将数组元素转换为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
tempStr3 = tempStr3[2..myLength-3]
reportStr = "In the first quarter we sold " + tempStr3 + " " + tempStr0 + "(s)."
puts reportStr
Run Code Online (Sandbox Code Playgroud)

一般来说.

但是,如何做到更优雅的"红宝石"方式呢?

小智 32

您可以使用该.join方法.

例如:

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

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

=> Apple, Pear, Banana
Run Code Online (Sandbox Code Playgroud)


Agi*_*gis 3

使用插值代替串联:

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

它更惯用、更高效、需要更少的打字并自动to_s为您呼叫。