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

标签 ruby arrays string version string-interpolation

我的问题是关于如何在没有括号和引号的情况下在 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/

相关文章:

c++ - 检查字符串是否相同C++

ruby - 括号运算符对 Ruby 中的 FixNum 做了什么?

arrays - Fortran 中的数组边界检查 - 这危险吗?

python - 如何使用imread将matplotlib中预定义值为 "n"的png读入n x n数组

python - 如何在 numpy 中创建 2D "rect"数组(1's, else 0' 的方 block )?

javascript - 根据不同的参数javascript创建一个字符串

ruby - 在具有组合因素的 RSpec 中组织测试的最佳方法

具有多个接口(interface)的系统上的 Ruby 套接字绑定(bind)

允许其子类注册回调的 Ruby 基类

r - 仅获取 R 中匹配的字符串部分