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

Jak*_*zok 8 ruby arrays hash

假设我们有一个哈希:

flash = {}
flash[:error] = "This is an error."
flash[:info] = "This is an information."
Run Code Online (Sandbox Code Playgroud)

我想将其转换为字符串:

"<div class='error'>This is an error.</div><div class='info'>This is an information".
Run Code Online (Sandbox Code Playgroud)

在漂亮的一个班轮;)

我发现了类似的东西:

flash.to_a.collect{|item| "<div class='#{item[0]}'>#{item[1]}</div>"}.join
Run Code Online (Sandbox Code Playgroud)

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

mol*_*olf 24

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

flash.collect { |k, v| "<div class='#{k}'>#{v}</div>" }.join
Run Code Online (Sandbox Code Playgroud)