Reputation: 824
I have an array of hashes generated by map
arr = current_order.order_items.map{|oi|[{name:oi.name,price:oi.price}]
[{:name=>"Jacket", :price=>300},
{:name=>"Bag", :price=>650 },
{:name=>"Suit", :price=>300}].to_s
i need to make a string from it like this
name: Jacket,price:300
name: Bag,price:650
name: Suit,price:300
What i did it gsub
every needed element like gsub(':size=>','size:')
but it looks very ugly
Need more convenient solution for this
Upvotes: 1
Views: 109
Reputation: 359
You could do something like:
map
over the array to gain pretty printed strings for each.
def pretty_print(hash)
hash.map {|key, value| "#{key}: #{value}"}.join(', ')
end
arr.map {|hash| pretty_print(hash)}
Upvotes: 3
Reputation: 1995
If keys are predetermined:
arr.map { |item| "name:#{ item[:name] }, price:#{ item[:price] }" }.join("\n")
If not:
arr.map { |item| item.map { |k, v| "#{ k }:#{ v }" }.join(', ') }.join("\n")
Upvotes: 2