1

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

0

2 Answers 2

3

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)}
    
Sign up to request clarification or add additional context in comments.

Comments

2

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.