Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove brackets and quotation marks from array Ruby

I have the below class method:

def self.product(basket)
  Product.find(basket.to_a).collect do |product| 
    product.name + " " + product.size + " " + product.color
  end
end

The above produces the following:

["T-Shirt Medium Grey", "Sweatshirt Medium Black"]

I've tried the following:

def self.product(basket)
  a = Product.find(basket.to_a).collect do |product| 
    product.name + " " + product.size + " " + product.color
  end
  b = a.shift.strip
end

But this ends up only giving me the first part of the array T-shirt Medium Grey

I'm looking for it to give me

T-shirt Medium Grey, Sweatshirt Medium Black

Can anyone help?

Thanks

like image 878
Robbo Avatar asked May 08 '14 10:05

Robbo


2 Answers

Your problem is how to customize displaying array content. One of possible solution is converting to string using Array#join method:

a.join(', ')
# => "T-Shirt Medium Grey, Sweatshirt Medium Black"
like image 121
Marek Lipka Avatar answered Sep 26 '22 20:09

Marek Lipka


This should work:

def self.product(basket)
  Product.find(basket.to_a).map{|product| [product.name, product.size, product.color].join(" ")}.join(', ')
end
like image 39
TCSGrad Avatar answered Sep 25 '22 20:09

TCSGrad