ruby 1.9 how to convert array to string without brackets

后端 未结 4 658
闹比i
闹比i 2021-02-13 17:03

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

4条回答
  •  借酒劲吻你
    2021-02-13 17:46

    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.
    

提交回复
热议问题