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

时间:2009-06-24 13:17:35

标签: ruby arrays hash

假设我们有一个哈希:

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

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

5 个答案:

答案 0 :(得分:24)

Hash包含Enumerable,因此您可以使用collect

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

答案 1 :(得分:0)

您可以使用

获取哈希中的密钥
flash.keys

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

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

这样做可以吗?

答案 2 :(得分:0)

inject非常方便:

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

答案 3 :(得分:0)

[:info, :error].collect { |k| "<div class=\"#{k}\">#{flash[k]}</div>" }.join

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

答案 4 :(得分: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>