【问题标题】:RoR string from array来自数组的 RoR 字符串
【发布时间】:2016-03-27 10:54:33
【问题描述】:

我有一个由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

我需要像这样从中创建一个字符串

name: Jacket,price:300
name: Bag,price:650
name: Suit,price:300

我做了什么gsub 每个需要的元素,比如gsub(':size=>','size:')

但是看起来很丑

需要更方便的解决方案

【问题讨论】:

    标签: ruby-on-rails arrays ruby string


    【解决方案1】:

    你可以这样做:

    1. 在哈希上定义一个函数以便为您漂亮地打印它。
    2. map 在数组上为每个获得漂亮的打印字符串。

      def pretty_print(hash)
        hash.map {|key, value| "#{key}: #{value}"}.join(', ')
      end
      arr.map {|hash| pretty_print(hash)}
      

    【讨论】:

      【解决方案2】:

      如果键是预先确定的:

      arr.map { |item| "name:#{ item[:name] }, price:#{ item[:price] }" }.join("\n")
      

      如果没有:

      arr.map { |item| item.map { |k, v| "#{ k }:#{ v }" }.join(', ')  }.join("\n")
      

      【讨论】:

        猜你喜欢
        • 2019-05-19
        • 2020-03-06
        • 2018-02-13
        • 1970-01-01
        • 2023-03-08
        • 2013-01-03
        • 2012-04-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多