ruby 1.9如何将数组转换为不带括号的字符串
我的问题是如何在没有得到括号和引号的情况下将数组元素转换为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
这产生了(想要的)输出
在第一季度,我们卖出了2个Apple。
ruby1.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`+’:无法将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
一般来说。
但是,如何做到更优雅的“ruby”方式呢?
使用插值而不是连接:
reportStr = "In the first quarter we sold #{myArray[3]} #{myArray[0]}(s)."
它更惯用,更高效,需要更少的输入并自动为您调用to_s
。
您可以使用.join
方法。
例如:
my_array = ["Apple", "Pear", "Banana"] my_array.join(', ') # returns string separating array elements with arg to `join` => Apple, Pear, Banana
如果你需要为多个水果做这个,最好的方法是转换数组并使用每个语句。
myArray = ["Apple", "Pear", "Banana", "2", "1", "12"] num_of_products = 3 tranformed = myArray.each_slice(num_of_products).to_a.transpose p tranformed #=> [["Apple", "2"], ["Pear", "1"], ["Banana", "12"]] tranformed.each do |fruit, amount| puts "In the first quarter we sold #{amount} #{fruit}#{amount=='1' ? '':'s'}." end #=> #In the first quarter we sold 2 Apples. #In the first quarter we sold 1 Pear. #In the first quarter we sold 12 Bananas.
您可以将其视为arrayToString()
array = array * " "
例如,
myArray = ["One.","_1_?! Really?!","Yes!"]
=>
"One.","_1_?! Really?!","Yes!"
myArray = myArray * " "
=>
"One. _1_?! Really?! Yes."