【问题标题】:Converting hash to string in Ruby在Ruby中将哈希转换为字符串
【发布时间】:2010-11-05 12:20:10
【问题描述】:

假设我们有一个哈希:

flash = {}
flash[:error] = "This is an error."
flash[:info] = "This is an information."

我想把它转成字符串:

"<div class='error'>This is an error.</div><div class='info'>This is an information".

在一个不错的班轮中;)

我发现了类似的东西:

flash.to_a.collect{|item| "<div class='#{item[0]}'>#{item[1]}</div>"}.join

这解决了我的问题,但也许哈希表类中有更好的解决方案?

【问题讨论】:

    标签: ruby arrays hash


    【解决方案1】:

    或者可能?

    class Hash
      def do_sexy
        collect { |k, v| "<div class='#{k}'>#{v}</div>" }.flatten
      end
    end
    
    flash = {}
    flash[:error] = "This is an error."
    flash[:info] = "This is an information."
    
    puts flash.do_sexy
    
    #outputs below
    <div class='error'>This is an error.</div>
    <div class='info'>This is an information.</div>
    

    【讨论】:

      【解决方案2】:
      [:info, :error].collect { |k| "<div class=\"#{k}\">#{flash[k]}</div>" }.join
      

      到目前为止,解决方案的唯一问题是您通常需要按特定顺序列出 flash 消息 - 而 hash 没有它,所以恕我直言,最好使用预定义的数组。

      【讨论】:

      • 你也可以使用 Ruby 1.9,如果你需要 Ruby 1.8,也可以借用 ActiveSupport 的OrderedHash
      【解决方案3】:

      inject 非常方便:

      flash.inject("") { |acc, kv| acc << "<div class='#{kv[0]}'>#{kv[1]}</div>" }
      

      【讨论】:

        【解决方案4】:

        您可以使用

        获取哈希中的键
        flash.keys
        

        然后你可以从那里构建一个新的字符串数组,然后加入它们。所以像

        flash.keys.collect {|k| "<div class=#{k}>#{flash[k]}</div>"}.join('')
        

        这样行吗?

        【讨论】:

          【解决方案5】:

          Hash包含Enumerable,所以你可以使用collect

          flash.collect { |k, v| "<div class='#{k}'>#{v}</div>" }.join
          

          【讨论】:

          • 是的,这就是我要找的东西 ;)
          猜你喜欢
          • 2013-07-06
          • 2014-09-24
          • 2015-04-02
          • 1970-01-01
          • 1970-01-01
          • 2014-07-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多