user2322409
user2322409

Reputation: 824

RoR string from array

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

Answers (2)

michaeldever
michaeldever

Reputation: 359

You could do something like:

  1. Define a function on a hash to pretty print it for you.
  2. 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

Babur Ussenakunov
Babur Ussenakunov

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

Related Questions