Robbo
Robbo

Reputation: 1312

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

Upvotes: 5

Views: 16192

Answers (2)

TCSGrad
TCSGrad

Reputation: 12108

This should work:

def self.product(basket)
  Product.find(basket.to_a).map{|product| [product.name, product.size, product.color].join(" ")}.join(', ')
end

Upvotes: 3

Marek Lipka
Marek Lipka

Reputation: 51151

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"

Upvotes: 21

Related Questions