ruby 1.9如何将数组转换为不带括号的字符串 [英] ruby 1.9 how to convert array to string without brackets

查看:197
本文介绍了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个苹果.

ruby​​ 1.9中的两行相同(不需要)

在第一季度,我们售出了[[2]] [[Apple]].

阅读文档后 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'+':无法将数组转换为字符串(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

通常可以正常工作.

然而,更优雅的红宝石"将是什么?怎么做到的?

解决方案

使用插值而不是串联:

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

它更惯用,更高效,需要更少的键入并自动为您调用to_s.

My question is about how to convert array elements to string in ruby 1.9 without getting the brackets and quotation marks. I've got an array (DB extract), from which I want to use to create a periodic report.

myArray = ["Apple", "Pear", "Banana", "2", "15", "12"]

In ruby 1.8 I had the following line

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

Which produced the (wanted) output

In the first quarter we sold 2 Apple(s).

The same two lines in ruby 1.9 produce (not wanted)

In the first quarter we sold ["2"] ["Apple"] (s).

After reading in the documentation Ruby 1.9.3 doc#Array#slice I thought I could produce code like

reportStr = "In the first quarter we sold " + myArray[3] + " " + myArray[0] + "(s)."
puts reportStr

which returns a runtime error

/home/test/example.rb:450:in `+': can't convert Array into String (TypeError)

My current solution is to remove brackets and quotation marks with a temporary string, like

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

which in general works.

However, what would be a more elegant "ruby" way how to do that?

解决方案

Use interpolation instead of concatenation:

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

It's more idiomatic, more efficient, requires less typing and automatically calls to_s for you.

这篇关于ruby 1.9如何将数组转换为不带括号的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆