简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM