在Ruby中将哈希转换为字符串
假设我们有一个哈希:
flash = {} flash[:error] = "This is an error." flash[:info] = "This is an information."
我想将其转换为字符串:
"This is an error.This is an information".
在漂亮的一个class轮;)
我找到了类似的东西:
flash.to_a.collect{|item| "#{item[1]}"}.join
这解决了我的问题,但也许在哈希表类中有更好的解决方案?
Hash
包含Enumerable
,因此您可以使用collect
:
flash.collect { |k, v| "#{v}" }.join
您可以使用哈希获取密钥
flash.keys
然后从那里你可以构建一个新的字符串数组,然后加入它们。 所以像
flash.keys.collect {|k| "#{flash[k]}"}.join('')
这样做诀窍吗?
inject
是无限的方便:
flash.inject("") { |acc, kv| acc << "#{kv[1]}" }
[:info, :error].collect { |k| "#{flash[k]}" }.join
到目前为止所提出的解决方案的唯一问题是您通常需要按特定顺序列出闪存消息 – 而散列没有它,所以恕我直言,它最好使用预定义的数组。
还是maby?
class Hash def do_sexy collect { |k, v| "#{v}" }.flatten end end flash = {} flash[:error] = "This is an error." flash[:info] = "This is an information." puts flash.do_sexy #outputs below This is an error. This is an information.