假设我们有一个散列:
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
这解决了我的问题,但也许哈希表类中内置了更好的解决方案?
最佳答案
Hash
包括 Enumerable
, 所以你可以使用 collect
:
flash.collect { |k, v| "<div class='#{k}'>#{v}</div>" }.join
关于ruby - 在 Ruby 中将散列转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1038275/