2009-06-24 183 views
8

比方说,我们有一个哈希:转换哈希字符串在Ruby中

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 

Tha t解决了我的问题,但也许有更好的解决方案在hashtable类中构建?

回答

24

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

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

是啊,这就是我一直在寻找;) – 2009-06-24 13:31:34

0

可以使用

flash.keys 

获得哈希键,然后从那里,你可以建立一个新的字符串数组然后加入他们。所以像

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

这是否有窍门?

0

inject是无限的方便:

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

与解决方案的唯一问题到目前为止提出的是,你通常需要列出特定的顺序闪光灯的消息 - 和哈希没有它,所以恕我直言最好使用预定义的数组。

+0

您也可以使用Ruby 1.9,或借用的ActiveSupport的`OrderedHash`如果您需要的Ruby 1.8。 – molf 2010-06-15 12:48:22

0

还是maby?

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>