ruby 1.9 how to convert array to string without brackets

蹲街弑〆低调 提交于 2019-12-03 10:48:25

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.

Santosh Sindham

You can use the .join method.

For example:

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

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

=> Apple, Pear, Banana

And if you need to do this for more than one fruit the best way is to transform the array and the use the each statement.

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.

You can think of this as arrayToString()

array = array * " "

E.g.,

myArray = ["One.","_1_?! Really?!","Yes!"]

=> "One.","_1_?! Really?!","Yes!"

myArray = myArray * " "

=> "One. _1_?! Really?! Yes."

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!