代码之家  ›  专栏  ›  技术社区  ›  Jakub Troszok

在Ruby中将哈希转换为字符串

  •  8
  • Jakub Troszok  · 技术社区  · 17 年前

    假设我们有一个哈希:

    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
    

    这解决了我的问题,但也许有更好的解决方案内置在hashtable类中?

    5 回复  |  直到 17 年前
        1
  •  24
  •   molf    17 年前

    Hash 包括 Enumerable ,以便使用 collect :

    flash.collect { |k, v| "<div class='#{k}'>#{v}</div>" }.join
    
        2
  •  0
  •   Bryan Ward    17 年前

    您可以使用

    flash.keys
    

    然后,您可以从那里构建一个新的字符串数组,然后连接它们。所以有点像

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

    这有什么作用吗?

        3
  •  0
  •   Ray Vernagus    17 年前

    inject 非常方便:

    flash.inject("") { |acc, kv| acc << "<div class='#{kv[0]}'>#{kv[1]}</div>" }
    
        4
  •  0
  •   Lukas Stejskal    17 年前
    [:info, :error].collect { |k| "<div class=\"#{k}\">#{flash[k]}</div>" }.join
    

    目前提供的解决方案的唯一问题是,您通常需要以特定的顺序列出闪存消息,而hash没有,所以imho最好使用预定义的数组。

        5
  •  0
  •   Simon Gate    17 年前

    还是马比?

    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>